Python Data Wrangling with Pandas for Data Analysis

Python Data Wrangling with Pandas for Data Analysis
in Data Science the Series

Introduction to Data Wrangling

Fundamentals of Data Analysis Processes

Input => Data (Files -> .csv, .txt, .xlsx, SQL, JSON, API, etc.)
1. Data Collection
2. Data Wrangling (Data Cleaning –> Data Transformation –> Data Enrichment)
3. Exploratory Data Analysis (EDA) –> Machine Learning and Data Visualization
4. Drawing Conclusion
Output => Communicate Results

1. Data Collection

Data Collection is the natural first step for any Data Analysis
เราไม่สามารถวิเคราะห์ข้อมูลที่เราไม่ได้มีได้ ในความเป็นจริง การวิเคราะห์ข้อมูลเราสามารถเริ่มต้นได้ก่อนที่จะมีข้อมูล เพราะเมื่อเราตัดสินใจแล้วว่าเราต้องการตรวจหรืออยากวิเคราะห์ข้อมูลอะไร เราก็ต้องคิดว่าข้อมูลประเภทใดที่เราต้องทำการรวบรวม ซึ่งจะเป็นประโยชน์สำหรับการวิเคราะห์ข้อมูลของเรา โดยข้อมูลจะมาในรูปแบบใดก็ได้

รูปแบบข้อมูลที่นิยมใช้ในการสร้าง Data Collection
1.1 Web Scraping ที่ดึงข้อมูลมาจาก HTML ของ Website (Python packages -> selenium, requests, scrapy, and beautifulsoup)
1.2 APIs (Application Programming Interface) ที่ให้บริการของ Web Services (requests package)
1.3 Databases เช่น SQL หรือ Database-Querying Language
1.4 Internet Resouces ที่เปิดให้ดาวน์โหลดจาก Website ต่าง ๆ เช่น [Open Government Data of Thailand](https://data.go.th/), [Kaggle](https://www.kaggle.com/datasets), [COVID-19 Data Hub](https://www.tableau.com/covid-19-coronavirus-data-resources), etc.
1.5 Log Files

2. Data Wrangling

Data Wrangling is the process of preparing the data and getting it into a format that can be used for analysis.
Big Problem คือ ข้อมูลบนโลกใบนี้ไม่ได้สวยหรูแบบที่คิด ต้องนำมาปรับแต่งใหม่ให้เข้าที่เข้าทางก่อนที่จะนำมาวิเคราะห์ได้
Preprocessing ขั้นการเตรียมข้อมูลเพื่อทำความสะอาดข้อมูล (Data Cleaning) เพื่อปรับแต่งข้อมูล พร้อมทั้งแปลงข้อมูล (Data Transformation) เพื่อเพิ่มประสิทธิภาพของข้อมูล (Data Enrichment) ให้เป็นรูปร่างที่ช่วยให้ส่วนงานทางด้านวิเคราะห์ข้อมูลสามารถนำไปใช้งานได้

รูปแบบของปัญหาที่พบเจอส่วนใหญ่

2.1 Human Errors ข้อมูลถูกบันทึกไม่ถูกต้อง เช่น พิมพ์ผิดใส่เลข 100 แทน 1,000 หรือข้อมูลที่บันทึกความหมายเหมือนกันแต่เขียนต่างกัน เช่น New York City, NYC และ nyc เป็นต้น

2.2 Computer Errors บางทีเครื่องไม่ได้บันทึกข้อมูล หรือเครื่องค้าง ทำให้ข้อมูลหายเกิดเป็น Missing Data

2.3 Unexpected Values ค่าที่ไม่คาดคิด บางทีเวลาที่บันทึกข้อมูลแล้วตัดสินใจใช้เครื่องหมาย ? สำหรับค่าที่ Missing Value ในคอลัมน์ตัวเลข Numeric ทำให้รายการข้อมูลทั้งหมดในคอลัมน์จะถือว่าเป็นข้อความ Text แทนค่าตัวเลข Numneric

2.4 Incomplete Information ข้อมูลไม่ครบถ้วน ลองนึกถึงแบบสำรวจที่มีคำถามเพิ่มเติม ไม่ใช่ทุกคนที่จะตอบ ดังนั้นเราจึงมีข้อมูลหายไป แต่ไม่ใช่เนื่องจาก Computer Error หรือ Human Error

2.5 Resolution ความละเอียดของข้อมูล บางทีข้อมูลอาจถูกเก็บรวบรวมต่อวินาที ในขณะที่เราต้องการข้อมูลแบบรายชั่วโมงสำหรับทำการวิเคราะห์ข้อมูล

2.6 Relevance of the Fields ความเกี่ยวข้องกันของ Fields บางครั้งข้อมูลที่ถูกรวบรวมหรือสร้างขึ้นมาแล้วได้ผลของ Fields ที่ยังไม่สอดคล้องกัน ทำให้การวิเคราะห์ยังไม่ได้ เพื่อให้มันอยู่ในสถานะใช้งานได้ เราจะต้องทำความสะอาดข้อมูล

2.7 Format of the Data ข้อมูลอาจถูกบันทึกในรูปแบบที่ไม่เอื้อต่อการวิเคราะห์ข้อมูล เราจะต้องทำการปรับ Format ของข้อมูลใหม่ให้ตรงกับความหมายที่ต้องการจะวิเคราะห์ข้อมูล

2.8 Misconfigurations in Data-Recording Process การกำหนดค่าผิดพลาดในกระบวนการบันทึกข้อมูล เช่น ข้อมูลที่มาจาก Sources แหล่งที่มาที่ Misconfiguration Trackers หรือ Webhook อาจจะไม่มีฟิลด์ Missing Fields หรือการส่ง Passing ในลำดับที่ไม่ถูกต้อง

Solutions:

Data Wrangling with Pandas –> เขียนโปรแกรม Python Programming มาใช้ในการเตรียมข้อมูล Preprocessing (Data Cleaning –> Data Transformation –> Data Enrichment)

Aggregating Pandas DataFrames –> การ Join DataFrames ด้วย Pandas

CASE STUDY: Rule-Based Anomaly Detection

3. Exploratory Data Analysis

During Exploratory Data Analysis (EDA), we use visualizations and summary statistics to get a better understanding of the data.

การวิเคราะห์ข้อมูลเชิงสำรวจ เราใช้การแสดงภาพข้อมูลและสถิติ มาช่วยวิเคราะห์ เพื่อสรุปให้เข้าใจข้อมูลได้ดีขึ้น เนื่องจากสมองของมนุษย์มีความชำนาญในการเลือกรูปแบบการมองเห็น การแสดงข้อมูลจึงมีความสำคัญต่อการวิเคราะห์ อันที่จริง คุณลักษณะบางอย่างของข้อมูลสามารถสังเกตได้เฉพาะในผ่านการ Plot Charts ขึ้นอยู่กับข้อมูลของเรา เราอาจ Plot Charts เพื่อดูว่าตัวแปรที่น่าสนใจมีวิวัฒนาการอย่างไรเมื่อเวลาผ่านไป เปรียบเทียบจำนวนการสังเกตของแต่ละหมวดหมู่ ค้นหาค่าผิดปกติ ดูการกระจายของตัวแปรต่อเนื่องและตัวแปรแบบไม่ต่อเนื่อง และอื่น ๆ อีกมากมาย ซึ่งคนที่ทำงานสายนี้ต้องมีความรู้ทางด้าน Statistics, Machine Learning และ Data Visualization ถึงจะเป็นนักวิเคราะห์ข้อมูลเชิงลึกได้อย่างมีประสิทธิภาพ

ความสัมพันธ์ของ Exploratory Data Analysis กับ Data Wrangling

3.1 Data จำเป็นต้องเตรียมก่อนทำ Exploratory Data Analysis

3.2 การแสดงภาพ Data Visualization ที่สร้างขึ้นระหว่างกระบวนการ EDA จะสามารถบอกถึงความจำเป็นในการทำความสะอาดข้อมูล Data Cleaning ได้

3.3 Data Wrangling จะใช้ Statistics เพื่อค้นหาปัญหาข้อมูลที่อาจเกิดขึ้น ในขณะที่ EDA ใช้เพื่อทำความเข้าใจข้อมูล โดยการทำความสะอาดที่ไม่เหมาะสมจะบิดเบือนสิ่งที่ค้นพบในขั้นของ EDA

3.4 Data Wrangling Skills will be required to get summary statistics across subsets of the data.

4. Drawing Conclusions

Drawing Conclusions ขั้นของการสรุปการวิเคราะห์ข้อมูล Data Analysis


หลังจากที่เราได้ทำ Data Collection รวบรวมข้อมูลสำหรับการวิเคราะห์ Data Wrangling (Data Cleaning –> Data Transformation –> Data Enrichment) และดำเนินการทำ Exploratory Data Analysis (EDA) อย่างละเอียดแล้ว ก็ถึงเวลาสรุปผล นี่คือที่ที่เราสรุปการค้นพบของเราจาก Exploratory Data Analysis (EDA) 

ตัดสินใจขั้นตอนต่อไป

4.1 เราสังเกตเห็นรูปแบบ Patterns หรือความสัมพันธ์ Relationships เมื่อแสดงข้อมูลเป็นภาพ Data Visualization หรือไม่?

4.2 เราสามารถคาดการณ์ Predictions จากข้อมูลของเราได้อย่างแม่นยำหรือไม่?

4.3 เหมาะสมที่จะย้ายไปสร้างแบบจำลองข้อมูล Data Modeling หรือไม่?

4.4 ข้อมูลมีการกระจาย Data Distribution อย่างไร?

4.5 ข้อมูลช่วยให้เราตอบคำถามที่เรามีหรือให้ข้อมูลเชิงลึก Business Insights เกี่ยวกับปัญหาที่เรากำลังตรวจสอบหรือไม่?

4.6 เราจำเป็นต้องรวบรวมข้อมูลใหม่ หรือ ข้อมูลเพิ่มเติมหรือไม่?

Let’s Understand All About Data Wrangling!

Data Wrangling Workshop #1 Crime

เปิด Website http://vis.stanford.edu/wrangler/

ทดลองฝึกปฏิบัติการทำ Data Wrangling ด้วยโปรแกรม Wrangler ซึ่งเป็น Interactive Tool สำหรับทำความสะอาดข้อมูล Data Cleaning และทำการแปลงข้อมูล Data Transformation ช่วยให้ใช้เวลาในการจัดรูปแบบน้อยลง และมีเวลามากขึ้นในการวิเคราะห์ข้อมูล Output ของการทดลองนี้ สามารถนำไปใช้ส่งออกข้อมูลเพื่อใช้ใน Excel, R, Tableau, Power BI, Google Data Studio, Protovis, etc.

http://vis.stanford.edu/wrangler/

Python Data Wrangling with Pandas

Aj. NesT the Series

Reference: Pyhton Data Cleaning Cookbook 2020

Practice 1: เช็คคุณภาพข้อมูลและทำความสะอาดข้อมูล

Measuring Data Quality and Data Cleaning of Your Data

Workshop 1: เริ่มดูข้อมูลของคุณก่อน

–> Getting a first look at your data

Input Datasets

Question 1: เราจะดูข้อมูลเบื้องต้นของ nls97.csv และ covidtotals.csv รวมทั้งจำนวน rows, columns และ data types ได้อย่างไร?

STEP 1: นำเข้า Datasets โดยทำการ Upload ไฟล์ nls97.csv และไฟล์ covidtotals.csv ขึ้น Google Colab (ไฟล์นี้จะถูกลบเมื่อเราหลุดจาก Session หรือปิด Browser) หรือ Python IDE เช่น PyCharm, VSCode, Juputer Notebook, etc.

STEP 2: นำเข้า pandas และ numpy libraries และทำการอ่านไฟล์ .csv ด้วย pandas เก็บเป็น Dataframe

ใช้คำสั่ง .read_csv()

import pandas as pd
import numpy as np
nls97 = pd.read_csv("/content/nls97.csv")
covidtotals = pd.read_csv("/content/covidtotals.csv", parse_dates = ['lastdate']) 
#คำสั่ง parse_dates จะทำการแปลง Column 'lastdate' ให้เป็น Datetime Type วันเดือนปี เพื่อให้สามารถนำไปเปรียบเทียบช่วงเวลาได้
print(nls97)
personid  gender  ...      colenrfeb17      colenroct17
0       100061  Female  ...  1. Not enrolled  1. Not enrolled
1       100139    Male  ...  1. Not enrolled  1. Not enrolled
2       100284    Male  ...  1. Not enrolled  1. Not enrolled
3       100292    Male  ...              NaN              NaN
4       100583    Male  ...  1. Not enrolled  1. Not enrolled
...        ...     ...  ...              ...              ...
8979    999291  Female  ...  1. Not enrolled  1. Not enrolled
8980    999406    Male  ...  1. Not enrolled  1. Not enrolled
8981    999543  Female  ...  1. Not enrolled  1. Not enrolled
8982    999698  Female  ...  1. Not enrolled  1. Not enrolled
8983    999963  Female  ...  1. Not enrolled  1. Not enrolled

[8984 rows x 89 columns]
print(covidtotals)
iso_code   lastdate        location  ...  median_age  gdp_per_capita  hosp_beds
0        AFG 2020-06-01     Afghanistan  ...        18.6        1803.987       0.50
1        ALB 2020-06-01         Albania  ...        38.0       11803.431       2.89
2        DZA 2020-06-01         Algeria  ...        29.1       13913.839       1.90
3        AND 2020-06-01         Andorra  ...         NaN             NaN        NaN
4        AGO 2020-06-01          Angola  ...        16.8        5819.495        NaN
..       ...        ...             ...  ...         ...             ...        ...
205      VNM 2020-06-01         Vietnam  ...        32.6        6171.884       2.60
206      ESH 2020-06-01  Western Sahara  ...        28.4             NaN        NaN
207      YEM 2020-06-01           Yemen  ...        20.3        1479.147       0.70
208      ZMB 2020-06-01          Zambia  ...        17.7        3689.251       2.00
209      ZWE 2020-06-01        Zimbabwe  ...        19.6        1899.775       1.70

[210 rows x 12 columns]

เรามาเริ่มตรวจ Data Quality ของ Dataset ชุด nls97.csv

STEP 3: ตั้งค่าและแสดง index และ size ของ nls97 data

ใช้คำสั่ง set_index()

nls97.set_index("personid", inplace=True) #กดได้แค่ครั้งเดียว ถ้ากดอีกครั้งต้องใช้คำสั่ง reset_index ก่อน
print(nls97)
#คำสั่ง set_index(" ", inplace=True) ทำการ set ให้ column 'personid' เป็น index จะอยู่ใน column แรกแทนที่คอมสร้างให้
#ถ้าต้องการกลับไปที่เดิมให้ใช้คำสั่ง reset_index แทน
    gender  birthmonth  ...      colenrfeb17      colenroct17
personid                      ...                                  
100061    Female           5  ...  1. Not enrolled  1. Not enrolled
100139      Male           9  ...  1. Not enrolled  1. Not enrolled
100284      Male          11  ...  1. Not enrolled  1. Not enrolled
100292      Male           4  ...              NaN              NaN
100583      Male           1  ...  1. Not enrolled  1. Not enrolled
...          ...         ...  ...              ...              ...
999291    Female           4  ...  1. Not enrolled  1. Not enrolled
999406      Male           7  ...  1. Not enrolled  1. Not enrolled
999543    Female           8  ...  1. Not enrolled  1. Not enrolled
999698    Female           5  ...  1. Not enrolled  1. Not enrolled
999963    Female           9  ...  1. Not enrolled  1. Not enrolled

[8984 rows x 88 columns]
print(nls97.index) #แสดงค่าของ Index
Int64Index([100061, 100139, 100284, 100292, 100583, 100833, 100931, 101089,
            101122, 101132,
            ...
            998997, 999031, 999053, 999087, 999103, 999291, 999406, 999543,
            999698, 999963],
           dtype='int64', name='personid', length=8984)
print(nls97.shape) #เช็คจำนวน rows และ columns
(8984, 88)
print(nls97.index.nunique()) #index.nunique แสดงจำนวนค่าที่ไม่ซ้ำกันใน index 
#ปรากฎว่าข้อมูล index คุณภาพดี เพราะไม่มีข้อมูลที่ซ้ำกัน
8984

STEP 4: แสดงจำนวน data types และ non-null value

ใช้คำสั่ง info()

print(nls97.info())
#คำสั่ง info() ทำการ list รายชื่อ colums ทั้งหมดและแสดงจำนวน complete values (และ missing values) และ data types 
# --> object คือคอลัมน์ที่เป็น text, string
# --> int64 คือคอลัมน์ที่เป็น integer ตัวเลขจำนวนเต็ม
# --> float64 คือคอลัมน์ที่เป็น float ตัวเลขที่มีทศนิยมได้
#memory usage: 6.4+ MB ขนาดไฟล์ที่ใช้
#จากข้อมูลจะเห็นว่า Dataframe มีคอลัมน์ที่สมบูรณ์แค่ 3 Columns คือ gender, birthmonth, birthyear เป็น complete values
#เพราะมี 8984 non-null rows สมบูรณ์ครบ => ถ้าเป็น 6663 non-null แสดงว่ามี missing values = 8984-6663 = 2321
<class 'pandas.core.frame.DataFrame'>
Int64Index: 8984 entries, 100061 to 999963
Data columns (total 88 columns):
 #   Column                 Non-Null Count  Dtype  
---  ------                 --------------  -----  
 0   gender                 8984 non-null   object 
 1   birthmonth             8984 non-null   int64  
 2   birthyear              8984 non-null   int64  
 3   highestgradecompleted  6663 non-null   float64
 4   maritalstatus          6672 non-null   object 
 5   childathome            4791 non-null   float64
 6   childnotathome         4791 non-null   float64
 7   wageincome             5091 non-null   float64
 8   weeklyhrscomputer      6710 non-null   object 
 9   weeklyhrstv            6711 non-null   object 
 10  nightlyhrssleep        6706 non-null   float64
 11  satverbal              1406 non-null   float64
 12  satmath                1407 non-null   float64
 13  gpaoverall             6004 non-null   float64
 14  gpaenglish             5798 non-null   float64
 15  gpamath                5766 non-null   float64
 16  gpascience             5684 non-null   float64
 17  highestdegree          8953 non-null   object 
 18  govprovidejobs         1833 non-null   object 
 19  govpricecontrols       1859 non-null   object 
 20  govhealthcare          1874 non-null   object 
 21  govelderliving         1872 non-null   object 
 22  govindhelp             1815 non-null   object 
 23  govunemp               1811 non-null   object 
 24  govincomediff          1775 non-null   object 
 25  govcollegefinance      1875 non-null   object 
 26  govdecenthousing       1847 non-null   object 
 27  govprotectenvironment  1860 non-null   object 
 28  weeksworked00          8603 non-null   float64
 29  weeksworked01          8564 non-null   float64
 30  weeksworked02          8556 non-null   float64
 31  weeksworked03          8490 non-null   float64
 32  weeksworked04          8458 non-null   float64
 33  weeksworked05          8403 non-null   float64
 34  weeksworked06          8340 non-null   float64
 35  weeksworked07          8272 non-null   float64
 36  weeksworked08          8186 non-null   float64
 37  weeksworked09          8146 non-null   float64
 38  weeksworked10          8054 non-null   float64
 39  weeksworked11          7968 non-null   float64
 40  weeksworked12          7747 non-null   float64
 41  weeksworked13          7680 non-null   float64
 42  weeksworked14          7612 non-null   float64
 43  weeksworked15          7389 non-null   float64
 44  weeksworked16          7068 non-null   float64
 45  weeksworked17          6670 non-null   float64
 46  colenrfeb97            1250 non-null   object 
 47  colenroct97            8501 non-null   object 
 48  colenrfeb98            8501 non-null   object 
 49  colenroct98            8888 non-null   object 
 50  colenrfeb99            8865 non-null   object 
 51  colenroct99            8851 non-null   object 
 52  colenrfeb00            8820 non-null   object 
 53  colenroct00            8805 non-null   object 
 54  colenrfeb01            8786 non-null   object 
 55  colenroct01            8758 non-null   object 
 56  colenrfeb02            8732 non-null   object 
 57  colenroct02            8698 non-null   object 
 58  colenrfeb03            8658 non-null   object 
 59  colenroct03            8622 non-null   object 
 60  colenrfeb04            8578 non-null   object 
 61  colenroct04            8546 non-null   object 
 62  colenrfeb05            8508 non-null   object 
 63  colenroct05            8471 non-null   object 
 64  colenrfeb06            8426 non-null   object 
 65  colenroct06            8407 non-null   object 
 66  colenrfeb07            8352 non-null   object 
 67  colenroct07            8331 non-null   object 
 68  colenrfeb08            8289 non-null   object 
 69  colenroct08            8280 non-null   object 
 70  colenrfeb09            8236 non-null   object 
 71  colenroct09            8193 non-null   object 
 72  colenrfeb10            8116 non-null   object 
 73  colenroct10            8091 non-null   object 
 74  colenrfeb11            8037 non-null   object 
 75  colenroct11            7972 non-null   object 
 76  colenrfeb12            7794 non-null   object 
 77  colenroct12            7754 non-null   object 
 78  colenrfeb13            7754 non-null   object 
 79  colenroct13            7754 non-null   object 
 80  colenrfeb14            7624 non-null   object 
 81  colenroct14            7469 non-null   object 
 82  colenrfeb15            7469 non-null   object 
 83  colenroct15            7469 non-null   object 
 84  colenrfeb16            7036 non-null   object 
 85  colenroct16            6733 non-null   object 
 86  colenrfeb17            6733 non-null   object 
 87  colenroct17            6734 non-null   object 
dtypes: float64(29), int64(2), object(57)
memory usage: 6.4+ MB
None

STEP 5: แสดงข้อมูล rows หัวบน

ใช้คำสั่ง .head() ถ้าต้องการแสดงหัวหางใช้คำสั่ง .tail()

print(nls97.head(3))
   gender  birthmonth  ...      colenrfeb17      colenroct17
personid                      ...                                  
100061    Female           5  ...  1. Not enrolled  1. Not enrolled
100139      Male           9  ...  1. Not enrolled  1. Not enrolled
100284      Male          11  ...  1. Not enrolled  1. Not enrolled

[3 rows x 88 columns]

STEP 6: ทำการปรับ rows–>columns และ columns–>rows

ใช้คำสั่ง .T (Trsnspose) เพื่อแสดงให้เห็นข้อมูลมากขึ้น

print(nls97.head(3).T)
personid                        100061           100139           100284
gender                          Female             Male             Male
birthmonth                           5                9               11
birthyear                         1980             1983             1984
highestgradecompleted               13               12                7
maritalstatus                  Married          Married    Never-married
...                                ...              ...              ...
colenroct15            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenrfeb16            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenroct16            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenrfeb17            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenroct17            1. Not enrolled  1. Not enrolled  1. Not enrolled

[88 rows x 3 columns]

เรามาเริ่มตรวจ Data Quality ของ Dataset ชุด covidtotals.csv

STEP 7: ตั้งค่าและแสดง index และ size ของ covidtotals.csv data

ใช้คำสั่ง set_index()

covidtotals.set_index("iso_code", inplace=True) #กดได้แค่ครั้งเดียว ถ้ากดอีกครั้งต้องใช้คำสั่ง reset_index ก่อน
print(covidtotals)
#คำสั่ง set_index(" ", inplace=True) ทำการ set ให้ column 'personid' เป็น index จะอยู่ใน column แรกแทนที่คอมสร้างให้
#ถ้าต้องการกลับไปที่เดิมให้ใช้คำสั่ง reset_index แทน
lastdate        location  ...  gdp_per_capita  hosp_beds
iso_code                             ...                           
AFG      2020-06-01     Afghanistan  ...        1803.987       0.50
ALB      2020-06-01         Albania  ...       11803.431       2.89
DZA      2020-06-01         Algeria  ...       13913.839       1.90
AND      2020-06-01         Andorra  ...             NaN        NaN
AGO      2020-06-01          Angola  ...        5819.495        NaN
...             ...             ...  ...             ...        ...
VNM      2020-06-01         Vietnam  ...        6171.884       2.60
ESH      2020-06-01  Western Sahara  ...             NaN        NaN
YEM      2020-06-01           Yemen  ...        1479.147       0.70
ZMB      2020-06-01          Zambia  ...        3689.251       2.00
ZWE      2020-06-01        Zimbabwe  ...        1899.775       1.70

[210 rows x 11 columns]
print(covidtotals.index) #แสดงค่าของ Index
Index(['AFG', 'ALB', 'DZA', 'AND', 'AGO', 'AIA', 'ATG', 'ARG', 'ARM', 'ABW',
       ...
       'VIR', 'URY', 'UZB', 'VAT', 'VEN', 'VNM', 'ESH', 'YEM', 'ZMB', 'ZWE'],
      dtype='object', name='iso_code', length=210)
print(covidtotals.shape) #เช็คจำนวน rows และ columns
(210, 11)
print(covidtotals.index.nunique()) #index.nunique แสดงจำนวนค่าที่ไม่ซ้ำกันใน index 
#ปรากฎว่าข้อมูล index คุณภาพดี เพราะไม่มีข้อมูลที่ซ้ำกัน
210

STEP 8: แสดงจำนวน data types และ non-null value

ใช้คำสั่ง info()

print(covidtotals.info())
#คำสั่ง info() ทำการ list รายชื่อ colums ทั้งหมดและแสดงจำนวน complete values (และ missing values) และ data types 
# --> datetime64 คือคอลัมน์ที่เป็น datetime ค่าวันเดือนปี
# --> object คือคอลัมน์ที่เป็น text, string
# --> int64 คือคอลัมน์ที่เป็น integer ตัวเลขจำนวนเต็ม
# --> float64 คือคอลัมน์ที่เป็น float ตัวเลขที่มีทศนิยมได้
#memory usage: 19.7+ KB ขนาดไฟล์ที่ใช้
#จากข้อมูลจะเห็นว่า Dataframe มีคอลัมน์ที่สมบูรณ์แค่ 5 Columns เป็น complete values 
#เพราะมี 210 non-null rows สมบูรณ์ครบ => ถ้าเป็น 209 non-null แสดงว่ามี missing values = 210-209 = 1
<class 'pandas.core.frame.DataFrame'>
Index: 210 entries, AFG to ZWE
Data columns (total 11 columns):
 #   Column           Non-Null Count  Dtype         
---  ------           --------------  -----         
 0   lastdate         210 non-null    datetime64[ns]
 1   location         210 non-null    object        
 2   total_cases      210 non-null    int64         
 3   total_deaths     210 non-null    int64         
 4   total_cases_pm   209 non-null    float64       
 5   total_deaths_pm  209 non-null    float64       
 6   population       210 non-null    float64       
 7   pop_density      198 non-null    float64       
 8   median_age       186 non-null    float64       
 9   gdp_per_capita   182 non-null    float64       
 10  hosp_beds        164 non-null    float64       
dtypes: datetime64[ns](1), float64(7), int64(2), object(1)
memory usage: 19.7+ KB
None

STEP 9: แสดงการสุ่มจำนวนข้อมูล Sample กลุ่มตัวอย่างแบบ Random

ใช้คำสั่ง .sample(n, random_state=k)

n คือ จำนวนข้อมูล sample ที่ต้องการสุ่ม

k คือ ค่า seed ที่กำหนดการ random กลุ่มข้อมูล จะเป็นเลขจำนวนเต็ม ถ้ากำหนดเลขเดิม ผลการ split ก็เหมือนเดิม

print(covidtotals.sample(3, random_state=1))
   lastdate        location  ...  gdp_per_capita  hosp_beds
iso_code                             ...                           
COG      2020-06-01           Congo  ...        4881.406        NaN
THA      2020-06-01        Thailand  ...       16277.671       2.10
CZE      2020-06-01  Czech Republic  ...       32605.906       6.63

[3 rows x 11 columns]

STEP 10: ทำการปรับ rows–>columns และ columns–>rows

ใช้คำสั่ง .T (Trsnspose) เพื่อแสดงให้เห็นข้อมูลมากขึ้น

print(covidtotals.sample(3, random_state=1).T)
<code>iso_code                         COG                  THA                  CZE
lastdate         2020-06-01 00:00:00  2020-06-01 00:00:00  2020-06-01 00:00:00
location                       Congo             Thailand       Czech Republic
total_cases                      611                 3081                 9273
total_deaths                      20                   57                  320
total_cases_pm               110.727                44.14              865.909
total_deaths_pm                3.624                0.817               29.881
population               5.51809e+06             6.98e+07           1.0709e+07
pop_density                   15.405              135.132              137.176
median_age                        19                 40.1                 43.3
gdp_per_capita               4881.41              16277.7              32605.9
hosp_beds                        NaN                  2.1                 6.63
</code>

Workshop 2: การเลือกและจัดระเบียบคอลัมน์

–> Selecting and Organizing Columns

Input Datasets

  • nls97.csv – the National Longitudinal Survey (NLS) 1997-2017.

Question 2: เราจะสำรวจวิธีการเลือกและจัดระเบียบให้กับคอลัมน์ด้วยวิธีการใด?

STEP 1: นำเข้า Datasets โดยทำการ Upload ไฟล์ nls97.csv ขึ้น Google Colab (ไฟล์นี้จะถูกลบเมื่อเราหลุดจาก Session หรือปิด Browser) หรือ Python IDE เช่น PyCharm, VSCode, Juputer Notebook, etc.

STEP 2: นำเข้า pandas และ numpy libraries

STEP 3: ทำการอ่านไฟล์ .csv ด้วย pandas เก็บเป็น Dataframe

ใช้คำสั่ง .read_csv()

STEP 4: ตั้งค่าและแสดง index และ size ของ nls97 data

ใช้คำสั่ง set_index()

STEP 5: แสดงจำนวน data types และ non-null value

ใช้คำสั่ง info()

import pandas as pd
import numpy as np
nls97 = pd.read_csv("/content/nls97.csv")
nls97.set_index("personid", inplace=True)
print(nls97)
print(nls97.info())
gender  birthmonth  ...      colenrfeb17      colenroct17
personid                      ...                                  
100061    Female           5  ...  1. Not enrolled  1. Not enrolled
100139      Male           9  ...  1. Not enrolled  1. Not enrolled
100284      Male          11  ...  1. Not enrolled  1. Not enrolled
100292      Male           4  ...              NaN              NaN
100583      Male           1  ...  1. Not enrolled  1. Not enrolled
...          ...         ...  ...              ...              ...
999291    Female           4  ...  1. Not enrolled  1. Not enrolled
999406      Male           7  ...  1. Not enrolled  1. Not enrolled
999543    Female           8  ...  1. Not enrolled  1. Not enrolled
999698    Female           5  ...  1. Not enrolled  1. Not enrolled
999963    Female           9  ...  1. Not enrolled  1. Not enrolled

[8984 rows x 88 columns]
<class 'pandas.core.frame.DataFrame'>
Int64Index: 8984 entries, 100061 to 999963
Data columns (total 88 columns):
 #   Column                 Non-Null Count  Dtype  
---  ------                 --------------  -----  
 0   gender                 8984 non-null   object 
 1   birthmonth             8984 non-null   int64  
 2   birthyear              8984 non-null   int64  
 3   highestgradecompleted  6663 non-null   float64
 4   maritalstatus          6672 non-null   object 
 5   childathome            4791 non-null   float64
 6   childnotathome         4791 non-null   float64
 7   wageincome             5091 non-null   float64
 8   weeklyhrscomputer      6710 non-null   object 
 9   weeklyhrstv            6711 non-null   object 
 10  nightlyhrssleep        6706 non-null   float64
 11  satverbal              1406 non-null   float64
 12  satmath                1407 non-null   float64
 13  gpaoverall             6004 non-null   float64
 14  gpaenglish             5798 non-null   float64
 15  gpamath                5766 non-null   float64
 16  gpascience             5684 non-null   float64
 17  highestdegree          8953 non-null   object 
 18  govprovidejobs         1833 non-null   object 
 19  govpricecontrols       1859 non-null   object 
 20  govhealthcare          1874 non-null   object 
 21  govelderliving         1872 non-null   object 
 22  govindhelp             1815 non-null   object 
 23  govunemp               1811 non-null   object 
 24  govincomediff          1775 non-null   object 
 25  govcollegefinance      1875 non-null   object 
 26  govdecenthousing       1847 non-null   object 
 27  govprotectenvironment  1860 non-null   object 
 28  weeksworked00          8603 non-null   float64
 29  weeksworked01          8564 non-null   float64
 30  weeksworked02          8556 non-null   float64
 31  weeksworked03          8490 non-null   float64
 32  weeksworked04          8458 non-null   float64
 33  weeksworked05          8403 non-null   float64
 34  weeksworked06          8340 non-null   float64
 35  weeksworked07          8272 non-null   float64
 36  weeksworked08          8186 non-null   float64
 37  weeksworked09          8146 non-null   float64
 38  weeksworked10          8054 non-null   float64
 39  weeksworked11          7968 non-null   float64
 40  weeksworked12          7747 non-null   float64
 41  weeksworked13          7680 non-null   float64
 42  weeksworked14          7612 non-null   float64
 43  weeksworked15          7389 non-null   float64
 44  weeksworked16          7068 non-null   float64
 45  weeksworked17          6670 non-null   float64
 46  colenrfeb97            1250 non-null   object 
 47  colenroct97            8501 non-null   object 
 48  colenrfeb98            8501 non-null   object 
 49  colenroct98            8888 non-null   object 
 50  colenrfeb99            8865 non-null   object 
 51  colenroct99            8851 non-null   object 
 52  colenrfeb00            8820 non-null   object 
 53  colenroct00            8805 non-null   object 
 54  colenrfeb01            8786 non-null   object 
 55  colenroct01            8758 non-null   object 
 56  colenrfeb02            8732 non-null   object 
 57  colenroct02            8698 non-null   object 
 58  colenrfeb03            8658 non-null   object 
 59  colenroct03            8622 non-null   object 
 60  colenrfeb04            8578 non-null   object 
 61  colenroct04            8546 non-null   object 
 62  colenrfeb05            8508 non-null   object 
 63  colenroct05            8471 non-null   object 
 64  colenrfeb06            8426 non-null   object 
 65  colenroct06            8407 non-null   object 
 66  colenrfeb07            8352 non-null   object 
 67  colenroct07            8331 non-null   object 
 68  colenrfeb08            8289 non-null   object 
 69  colenroct08            8280 non-null   object 
 70  colenrfeb09            8236 non-null   object 
 71  colenroct09            8193 non-null   object 
 72  colenrfeb10            8116 non-null   object 
 73  colenroct10            8091 non-null   object 
 74  colenrfeb11            8037 non-null   object 
 75  colenroct11            7972 non-null   object 
 76  colenrfeb12            7794 non-null   object 
 77  colenroct12            7754 non-null   object 
 78  colenrfeb13            7754 non-null   object 
 79  colenroct13            7754 non-null   object 
 80  colenrfeb14            7624 non-null   object 
 81  colenroct14            7469 non-null   object 
 82  colenrfeb15            7469 non-null   object 
 83  colenroct15            7469 non-null   object 
 84  colenrfeb16            7036 non-null   object 
 85  colenroct16            6733 non-null   object 
 86  colenrfeb17            6733 non-null   object 
 87  colenroct17            6734 non-null   object 
dtypes: float64(29), int64(2), object(57)
memory usage: 6.1+ MB
None

STEP 6: แปลง data types ของ columns ที่เป็น object ให้เป็น category เพื่อทำข้อมูลให้เหมาะสม

data typs –> category เหมาะสำหรับข้อมูลที่มีซ้ำ ๆ กัน ที่ไม่ค่อยต่างกันมาก ช่วยในการเรื่องการประหยัด Memory

ใช้คำสั่ง .loc[ ] ทำการ Filter เข้าถึงข้อมูล –> คำสั่ง pandas หมวด Filter จะมีทั้ง .loc [ ], .iloc [ ], .query [ ]

ใช้คำสั่ง .select_dtypes ทำการเลือก data types

ใช้คำสั่ง .apply(lamba function) เพื่อแปลงข้อมูล

ใช้คำสั่ง .astype ทำการแปลง data types

nls97.loc[:, nls97.dtypes == 'object'] = \
  nls97.select_dtypes(['object']). \
  apply(lambda x: x.astype('category'))  
print(nls97.info())                         
#เครื่องหมาย \ คือ เพื่อเชื่อมประโยคให้ต่อกันในอีกบรรทัดนึง
#Syntax --> .loc['row_name' , 'column_name'] สนใจชื่อ
#Syntax --> .iloc['row_index_number' , 'column_index_number'] สนใจตำแหน่ง index ของ row และ column
#loc[: Filter ชื่อทุกตัว, ที่มีเงื่อนไขเป็น 'object'] และทำการเลือก loc ย่อมาจาก location based
#ทำการแปลง colums ที่เป็น 'object' --> 'category'
#ผลปรากฎว่า 'category' ช่วยลด memory (2.7 MB) ได้มากกว่า 'object' (6.1+ MB)
<class 'pandas.core.frame.DataFrame'>
Int64Index: 8984 entries, 100061 to 999963
Data columns (total 88 columns):
 #   Column                 Non-Null Count  Dtype   
---  ------                 --------------  -----   
 0   gender                 8984 non-null   category
 1   birthmonth             8984 non-null   int64   
 2   birthyear              8984 non-null   int64   
 3   highestgradecompleted  6663 non-null   float64 
 4   maritalstatus          6672 non-null   category
 5   childathome            4791 non-null   float64 
 6   childnotathome         4791 non-null   float64 
 7   wageincome             5091 non-null   float64 
 8   weeklyhrscomputer      6710 non-null   category
 9   weeklyhrstv            6711 non-null   category
 10  nightlyhrssleep        6706 non-null   float64 
 11  satverbal              1406 non-null   float64 
 12  satmath                1407 non-null   float64 
 13  gpaoverall             6004 non-null   float64 
 14  gpaenglish             5798 non-null   float64 
 15  gpamath                5766 non-null   float64 
 16  gpascience             5684 non-null   float64 
 17  highestdegree          8953 non-null   category
 18  govprovidejobs         1833 non-null   category
 19  govpricecontrols       1859 non-null   category
 20  govhealthcare          1874 non-null   category
 21  govelderliving         1872 non-null   category
 22  govindhelp             1815 non-null   category
 23  govunemp               1811 non-null   category
 24  govincomediff          1775 non-null   category
 25  govcollegefinance      1875 non-null   category
 26  govdecenthousing       1847 non-null   category
 27  govprotectenvironment  1860 non-null   category
 28  weeksworked00          8603 non-null   float64 
 29  weeksworked01          8564 non-null   float64 
 30  weeksworked02          8556 non-null   float64 
 31  weeksworked03          8490 non-null   float64 
 32  weeksworked04          8458 non-null   float64 
 33  weeksworked05          8403 non-null   float64 
 34  weeksworked06          8340 non-null   float64 
 35  weeksworked07          8272 non-null   float64 
 36  weeksworked08          8186 non-null   float64 
 37  weeksworked09          8146 non-null   float64 
 38  weeksworked10          8054 non-null   float64 
 39  weeksworked11          7968 non-null   float64 
 40  weeksworked12          7747 non-null   float64 
 41  weeksworked13          7680 non-null   float64 
 42  weeksworked14          7612 non-null   float64 
 43  weeksworked15          7389 non-null   float64 
 44  weeksworked16          7068 non-null   float64 
 45  weeksworked17          6670 non-null   float64 
 46  colenrfeb97            1250 non-null   category
 47  colenroct97            8501 non-null   category
 48  colenrfeb98            8501 non-null   category
 49  colenroct98            8888 non-null   category
 50  colenrfeb99            8865 non-null   category
 51  colenroct99            8851 non-null   category
 52  colenrfeb00            8820 non-null   category
 53  colenroct00            8805 non-null   category
 54  colenrfeb01            8786 non-null   category
 55  colenroct01            8758 non-null   category
 56  colenrfeb02            8732 non-null   category
 57  colenroct02            8698 non-null   category
 58  colenrfeb03            8658 non-null   category
 59  colenroct03            8622 non-null   category
 60  colenrfeb04            8578 non-null   category
 61  colenroct04            8546 non-null   category
 62  colenrfeb05            8508 non-null   category
 63  colenroct05            8471 non-null   category
 64  colenrfeb06            8426 non-null   category
 65  colenroct06            8407 non-null   category
 66  colenrfeb07            8352 non-null   category
 67  colenroct07            8331 non-null   category
 68  colenrfeb08            8289 non-null   category
 69  colenroct08            8280 non-null   category
 70  colenrfeb09            8236 non-null   category
 71  colenroct09            8193 non-null   category
 72  colenrfeb10            8116 non-null   category
 73  colenroct10            8091 non-null   category
 74  colenrfeb11            8037 non-null   category
 75  colenroct11            7972 non-null   category
 76  colenrfeb12            7794 non-null   category
 77  colenroct12            7754 non-null   category
 78  colenrfeb13            7754 non-null   category
 79  colenroct13            7754 non-null   category
 80  colenrfeb14            7624 non-null   category
 81  colenroct14            7469 non-null   category
 82  colenrfeb15            7469 non-null   category
 83  colenroct15            7469 non-null   category
 84  colenrfeb16            7036 non-null   category
 85  colenroct16            6733 non-null   category
 86  colenrfeb17            6733 non-null   category
 87  colenroct17            6734 non-null   category
dtypes: category(57), float64(29), int64(2)
memory usage: 2.7 MB
None

STEP 7: วิธีการเลือก column แบบ 1 column โดยใช้ [ ] index oprator, .loc, .iloc ของ pandas

Select a column using the pandas [ ] bracket operator, and the loc and iloc accessors.

แบบที่ 1 ใช้ [ ‘column_name’ ] เลือก column ที่ต้องการ แบบ Series

analysisdemo = nls97['gender']          #[ ] เข้าถึง Series
print(type(analysisdemo))
print(analysisdemo)
<class 'pandas.core.series.Series'>
personid
100061    Female
100139      Male
100284      Male
100292      Male
100583      Male
           ...  
999291    Female
999406      Male
999543    Female
999698    Female
999963    Female
Name: gender, Length: 8984, dtype: category
Categories (2, object): ['Female', 'Male']

แบบที่ 2 ใช้ [[ ‘column_name’ ]] เลือก column ที่ต้องการ แบบ DataFrame

analysisdemo = nls97[['gender']]       # [[ 'column_name' ]] เข้าถึง DataFrame เอาทุก rows
print(type(analysisdemo))
print(analysisdemo)
<class 'pandas.core.frame.DataFrame'>
          gender
personid        
100061    Female
100139      Male
100284      Male
100292      Male
100583      Male
...          ...
999291    Female
999406      Male
999543    Female
999698    Female
999963    Female

[8984 rows x 1 columns]

แบบที่ 3 ใช้คำสั่ง .loc เลือกเข้าถึงทุก rows และเลือก column แบบใช้ชื่อ ‘column_name’

ในที่นี้ผลลัพธ์เหมือนกันกับข้างบน

analysisdemo = nls97.loc[:, ['gender']]   #    [     :     ,    [    ]    ]  : => #slicing
print(type(analysisdemo))                 #.loc['row_name' , 'column_name']
print(analysisdemo)
<class 'pandas.core.frame.DataFrame'>
          gender
personid        
100061    Female
100139      Male
100284      Male
100292      Male
100583      Male
...          ...
999291    Female
999406      Male
999543    Female
999698    Female
999963    Female

[8984 rows x 1 columns]

แบบที่ 4 ใช้คำสั่ง .iloc เลือกเข้าถึงทุก rows และเลือก column แบบใช้เลขตำแหน่ง index ของ column ที่ต้องการ

analysisdemo = nls97.iloc[:, [0]]      #     [     :     ,         [ int index ] ]  : => #slicing
print(type(analysisdemo))              #.iloc['row_index_number' , 'column_index_number'] 
print(analysisdemo)
#ทดลองเปลี่ยนเลขตำแหน่ง index เพื่อเข้าถึง columns ต่าง ๆ
<class 'pandas.core.frame.DataFrame'>
          gender
personid        
100061    Female
100139      Male
100284      Male
100292      Male
100583      Male
...          ...
999291    Female
999406      Male
999543    Female
999698    Female
999963    Female

[8984 rows x 1 columns]

STEP 8: วิธีการเลือกแบบหลาย columns โดยใช้ [ ] และ .loc

Select multiple columns from a pandas data frame

Use the bracket operator and loc to select a few columns:

แบบที่ 1 ใช้ [ [‘ column_name1 ‘, ‘ column_name2’, ‘ column_name3 ‘, … ] ] เลือกหลาย columns

analysisdemo = nls97[['gender','maritalstatus','highestgradecompleted']] #ให้เปิดไฟล์ nls97 ดู data ไปด้วย
print(analysisdemo.shape)  #.shape แสดงจำนวน (rows, columns)
print(analysisdemo.head()) #.head() Default จะแสดงให้เห็น 5 rows แต่ความเป็นจริงเข้าถึงทุก rows อยู่แล้ว
(8984, 3)
          gender  maritalstatus  highestgradecompleted
personid                                              
100061    Female        Married                   13.0
100139      Male        Married                   12.0
100284      Male  Never-married                    7.0
100292      Male            NaN                    NaN
100583      Male        Married                   13.0

แบบที่ 2 ใช้คำสั่ง .loc[ : , [ ‘column_name1’, ‘ column_name2 ‘, … ] ] ใช้ : แปลว่า เลือกทุก rows เช่นเดียวกัน

ผลลัพธ์จะได้เหมือนกัน

analysisdemo = nls97.loc[:,['gender','maritalstatus','highestgradecompleted']]
print(analysisdemo.shape)
print(analysisdemo.head())
(8984, 3)
          gender  maritalstatus  highestgradecompleted
personid                                              
100061    Female        Married                   13.0
100139      Male        Married                   12.0
100284      Male  Never-married                    7.0
100292      Male            NaN                    NaN
100583      Male        Married                   13.0

STEP 9: วิธีการเลือกแบบหลาย columns ตามรายการ list ของ columns

Select multiple columns based on a list of columns เป็นการจัดกลุ่มของ columns จะมีประโยชน์มากในการวิเคราะห์ข้อมูล

If you are selecting more than a few columns, it is helpful to create the list of column names separately. Here, we create a keyvars list of key variables for analysis:

keyvars = ['gender', 'maritalstatus', 'highestgradecompleted', 'wageincome',
           'gpaoverall', 'weeksworked17', 'colenroct17']
analysiskeys = nls97[keyvars]
print(analysiskeys.info())
<class 'pandas.core.frame.DataFrame'>
Int64Index: 8984 entries, 100061 to 999963
Data columns (total 7 columns):
 #   Column                 Non-Null Count  Dtype   
---  ------                 --------------  -----   
 0   gender                 8984 non-null   category
 1   maritalstatus          6672 non-null   category
 2   highestgradecompleted  6663 non-null   float64 
 3   wageincome             5091 non-null   float64 
 4   gpaoverall             6004 non-null   float64 
 5   weeksworked17          6670 non-null   float64 
 6   colenroct17            6734 non-null   category
dtypes: category(3), float64(4)
memory usage: 377.7 KB
None

STEP 10: วิธีการเลือก columns ด้วย Filter operator

Select all of the weeksworked## columns using the filter operator

ใช้คำสั่ง .filter() ผ่านตัวดำเนินการ like

analysiswork = nls97.filter(like="weeksworked")
print(analysiswork.info())
<class 'pandas.core.frame.DataFrame'>
Int64Index: 8984 entries, 100061 to 999963
Data columns (total 18 columns):
 #   Column         Non-Null Count  Dtype  
---  ------         --------------  -----  
 0   weeksworked00  8603 non-null   float64
 1   weeksworked01  8564 non-null   float64
 2   weeksworked02  8556 non-null   float64
 3   weeksworked03  8490 non-null   float64
 4   weeksworked04  8458 non-null   float64
 5   weeksworked05  8403 non-null   float64
 6   weeksworked06  8340 non-null   float64
 7   weeksworked07  8272 non-null   float64
 8   weeksworked08  8186 non-null   float64
 9   weeksworked09  8146 non-null   float64
 10  weeksworked10  8054 non-null   float64
 11  weeksworked11  7968 non-null   float64
 12  weeksworked12  7747 non-null   float64
 13  weeksworked13  7680 non-null   float64
 14  weeksworked14  7612 non-null   float64
 15  weeksworked15  7389 non-null   float64
 16  weeksworked16  7068 non-null   float64
 17  weeksworked17  6670 non-null   float64
dtypes: float64(18)
memory usage: 1.3 MB
None

STEP 11: วิธีการเลือก columns ด้วย Data Types

ใช้คำสั่ง .select_dtype() ในการเลือก columns ด้วย data type –> include=[ “data_type” ]

analysiscats = nls97.select_dtypes(include=["category"]) #ในที่นี้เลือกเฉพาะ data type ที่เป็น "category"
print(analysiscats.info())                               #ทดลองพิมพ์เป็น int64, float64
<class 'pandas.core.frame.DataFrame'>
Int64Index: 8984 entries, 100061 to 999963
Data columns (total 57 columns):
 #   Column                 Non-Null Count  Dtype   
---  ------                 --------------  -----   
 0   gender                 8984 non-null   category
 1   maritalstatus          6672 non-null   category
 2   weeklyhrscomputer      6710 non-null   category
 3   weeklyhrstv            6711 non-null   category
 4   highestdegree          8953 non-null   category
 5   govprovidejobs         1833 non-null   category
 6   govpricecontrols       1859 non-null   category
 7   govhealthcare          1874 non-null   category
 8   govelderliving         1872 non-null   category
 9   govindhelp             1815 non-null   category
 10  govunemp               1811 non-null   category
 11  govincomediff          1775 non-null   category
 12  govcollegefinance      1875 non-null   category
 13  govdecenthousing       1847 non-null   category
 14  govprotectenvironment  1860 non-null   category
 15  colenrfeb97            1250 non-null   category
 16  colenroct97            8501 non-null   category
 17  colenrfeb98            8501 non-null   category
 18  colenroct98            8888 non-null   category
 19  colenrfeb99            8865 non-null   category
 20  colenroct99            8851 non-null   category
 21  colenrfeb00            8820 non-null   category
 22  colenroct00            8805 non-null   category
 23  colenrfeb01            8786 non-null   category
 24  colenroct01            8758 non-null   category
 25  colenrfeb02            8732 non-null   category
 26  colenroct02            8698 non-null   category
 27  colenrfeb03            8658 non-null   category
 28  colenroct03            8622 non-null   category
 29  colenrfeb04            8578 non-null   category
 30  colenroct04            8546 non-null   category
 31  colenrfeb05            8508 non-null   category
 32  colenroct05            8471 non-null   category
 33  colenrfeb06            8426 non-null   category
 34  colenroct06            8407 non-null   category
 35  colenrfeb07            8352 non-null   category
 36  colenroct07            8331 non-null   category
 37  colenrfeb08            8289 non-null   category
 38  colenroct08            8280 non-null   category
 39  colenrfeb09            8236 non-null   category
 40  colenroct09            8193 non-null   category
 41  colenrfeb10            8116 non-null   category
 42  colenroct10            8091 non-null   category
 43  colenrfeb11            8037 non-null   category
 44  colenroct11            7972 non-null   category
 45  colenrfeb12            7794 non-null   category
 46  colenroct12            7754 non-null   category
 47  colenrfeb13            7754 non-null   category
 48  colenroct13            7754 non-null   category
 49  colenrfeb14            7624 non-null   category
 50  colenroct14            7469 non-null   category
 51  colenrfeb15            7469 non-null   category
 52  colenroct15            7469 non-null   category
 53  colenrfeb16            7036 non-null   category
 54  colenroct16            6733 non-null   category
 55  colenrfeb17            6733 non-null   category
 56  colenroct17            6734 non-null   category
dtypes: category(57)
memory usage: 580.0 KB
None

STEP 12: วิธีการเลือก columns ด้วย Data Types แบบชนิด number

ใช้คำสั่ง .select_dtypes(include=[“number”]) –> int64, float64

analysisnums = nls97.select_dtypes(include=["number"])
print(analysisnums.info())
<class 'pandas.core.frame.DataFrame'>
Int64Index: 8984 entries, 100061 to 999963
Data columns (total 31 columns):
 #   Column                 Non-Null Count  Dtype  
---  ------                 --------------  -----  
 0   birthmonth             8984 non-null   int64  
 1   birthyear              8984 non-null   int64  
 2   highestgradecompleted  6663 non-null   float64
 3   childathome            4791 non-null   float64
 4   childnotathome         4791 non-null   float64
 5   wageincome             5091 non-null   float64
 6   nightlyhrssleep        6706 non-null   float64
 7   satverbal              1406 non-null   float64
 8   satmath                1407 non-null   float64
 9   gpaoverall             6004 non-null   float64
 10  gpaenglish             5798 non-null   float64
 11  gpamath                5766 non-null   float64
 12  gpascience             5684 non-null   float64
 13  weeksworked00          8603 non-null   float64
 14  weeksworked01          8564 non-null   float64
 15  weeksworked02          8556 non-null   float64
 16  weeksworked03          8490 non-null   float64
 17  weeksworked04          8458 non-null   float64
 18  weeksworked05          8403 non-null   float64
 19  weeksworked06          8340 non-null   float64
 20  weeksworked07          8272 non-null   float64
 21  weeksworked08          8186 non-null   float64
 22  weeksworked09          8146 non-null   float64
 23  weeksworked10          8054 non-null   float64
 24  weeksworked11          7968 non-null   float64
 25  weeksworked12          7747 non-null   float64
 26  weeksworked13          7680 non-null   float64
 27  weeksworked14          7612 non-null   float64
 28  weeksworked15          7389 non-null   float64
 29  weeksworked16          7068 non-null   float64
 30  weeksworked17          6670 non-null   float64
dtypes: float64(29), int64(2)
memory usage: 2.2 MB
None

STEP 13: วิธีการจัดระเบียบ column โดยใช้ list ของ column names

Organize columns using lists of column names

demo = ['gender','birthmonth','birthyear']
highschoolrecord = ['satverbal','satmath','gpaoverall','gpaenglish','gpamath','gpascience']
govresp = ['govprovidejobs','govpricecontrols','govhealthcare','govelderliving','govindhelp',
          'govunemp','govincomediff','govcollegefinance','govdecenthousing','govprotectenvironment']
demoadult = ['highestgradecompleted','maritalstatus','childathome','childnotathome','wageincome',
            'weeklyhrscomputer','weeklyhrstv','nightlyhrssleep','highestdegree']
weeksworked = ['weeksworked00','weeksworked01','weeksworked02','weeksworked03','weeksworked04',
              'weeksworked05','weeksworked06',  'weeksworked07','weeksworked08','weeksworked09',
              'weeksworked10','weeksworked11','weeksworked12','weeksworked13','weeksworked14',
              'weeksworked15','weeksworked16','weeksworked17']
colenr = ['colenrfeb97','colenroct97','colenrfeb98','colenroct98','colenrfeb99',  'colenroct99',
          'colenrfeb00','colenroct00','colenrfeb01','colenroct01','colenrfeb02','colenroct02',
          'colenrfeb03','colenroct03','colenrfeb04','colenroct04','colenrfeb05','colenroct05',
          'colenrfeb06','colenroct06','colenrfeb07','colenroct07','colenrfeb08','colenroct08',
          'colenrfeb09','colenroct09','colenrfeb10','colenroct10','colenrfeb11','colenroct11',
          'colenrfeb12','colenroct12','colenrfeb13','colenroct13',  'colenrfeb14','colenroct14',
          'colenrfeb15','colenroct15','colenrfeb16','colenroct16','colenrfeb17','colenroct17']

STEP 14: สร้าง DataFrame ที่จัดระเบียบ columns ใหม่

Create the new, reorganized DataFrame

new_nls97 = nls97[demoadult + demo + highschoolrecord + govresp + weeksworked + colenr]
print(new_nls97.dtypes)
highestgradecompleted     float64
maritalstatus            category
childathome               float64
childnotathome            float64
wageincome                float64
                           ...   
colenroct15              category
colenrfeb16              category
colenroct16              category
colenrfeb17              category
colenroct17              category
Length: 88, dtype: object

STEP 15: ทำการสร้างไฟล์ new_nls97.csv เพื่อ export ไปใช้งาน

ใช้คำสั่ง ชื่อตัวแปรข้อมูล.to_csv(“/path/…”)

new_nls97.to_csv("/content/new_nls97.csv")

STEP 16: เราสามารถใช้คำสั่ง select_dtypes เพื่อเลือก columns ที่ยกเว้น data types ที่ไม่ต้องการเลือกได้

ใช้คำสั่ง select_dtypes(exclude=[” data_type “])

data_notcategoty = nls97.select_dtypes(exclude=["category"]) #ใส่ data types ที่ไม่ต้องการ
print(data_notcategoty.info())
<class 'pandas.core.frame.DataFrame'>
Int64Index: 8984 entries, 100061 to 999963
Data columns (total 31 columns):
 #   Column                 Non-Null Count  Dtype  
---  ------                 --------------  -----  
 0   highestgradecompleted  6663 non-null   float64
 1   childathome            4791 non-null   float64
 2   childnotathome         4791 non-null   float64
 3   wageincome             5091 non-null   float64
 4   nightlyhrssleep        6706 non-null   float64
 5   birthmonth             8984 non-null   int64  
 6   birthyear              8984 non-null   int64  
 7   satverbal              1406 non-null   float64
 8   satmath                1407 non-null   float64
 9   gpaoverall             6004 non-null   float64
 10  gpaenglish             5798 non-null   float64
 11  gpamath                5766 non-null   float64
 12  gpascience             5684 non-null   float64
 13  weeksworked00          8603 non-null   float64
 14  weeksworked01          8564 non-null   float64
 15  weeksworked02          8556 non-null   float64
 16  weeksworked03          8490 non-null   float64
 17  weeksworked04          8458 non-null   float64
 18  weeksworked05          8403 non-null   float64
 19  weeksworked06          8340 non-null   float64
 20  weeksworked07          8272 non-null   float64
 21  weeksworked08          8186 non-null   float64
 22  weeksworked09          8146 non-null   float64
 23  weeksworked10          8054 non-null   float64
 24  weeksworked11          7968 non-null   float64
 25  weeksworked12          7747 non-null   float64
 26  weeksworked13          7680 non-null   float64
 27  weeksworked14          7612 non-null   float64
 28  weeksworked15          7389 non-null   float64
 29  weeksworked16          7068 non-null   float64
 30  weeksworked17          6670 non-null   float64
dtypes: float64(29), int64(2)
memory usage: 2.2 MB
None

STEP 17: เราสามารถ Filter ชื่อ column ที่มีคำที่เราต้องการได้

The filter operator can also take a regular expression

ใช้คำสั่ง filter(regex=[ ‘word’ ])

data_wordincome = nls97.filter(regex='income') #ทดลองเปลี่ยนเป็น 'birth' หรือ 'gpa'
print(data_wordincome)
      wageincome govincomediff
personid                          
100061       12500.0           NaN
100139      120000.0           NaN
100284       58000.0           NaN
100292           NaN           NaN
100583       30000.0           NaN
...              ...           ...
999291       35000.0           NaN
999406      116000.0           NaN
999543           NaN           NaN
999698           NaN           NaN
999963       50000.0           NaN

[8984 rows x 2 columns]

Workshop 3: การเลือกแถว

–> Selecting Rows

Input Datasets

  • nls97.csv – the National Longitudinal Survey (NLS) 1997-2017.

Question 3: เราจะสำรวจวิธีการเลือกแถว Zoom In Zoom Out ข้อมูล ทำได้แบบไหนบ้าง?

STEP 1: นำเข้า Datasets โดยทำการ Upload ไฟล์ nls97.csv ขึ้น Google Colab (ไฟล์นี้จะถูกลบเมื่อเราหลุดจาก Session หรือปิด Browser) หรือ Python IDE เช่น PyCharm, VSCode, Juputer Notebook, etc.

STEP 2: ทำการอ่านไฟล์ .csv ด้วย pandas เก็บเป็น Dataframe

ใช้คำสั่ง .read_csv()

STEP 3: ตั้งค่าและแสดง index และ size ของ nls97 data

ใช้คำสั่ง set_index()

STEP 4: ตั้งค่าและแสดง index และ size ของ nls97 data

ใช้คำสั่ง set_index()

STEP 5: แสดงจำนวน data types และ non-null value

ใช้คำสั่ง info()

import pandas as pd
import numpy as np
nls97 = pd.read_csv("/content/nls97.csv")
nls97.set_index("personid", inplace=True)
print(nls97)
print(nls97.info())
gender  birthmonth  ...      colenrfeb17      colenroct17
personid                      ...                                  
100061    Female           5  ...  1. Not enrolled  1. Not enrolled
100139      Male           9  ...  1. Not enrolled  1. Not enrolled
100284      Male          11  ...  1. Not enrolled  1. Not enrolled
100292      Male           4  ...              NaN              NaN
100583      Male           1  ...  1. Not enrolled  1. Not enrolled
...          ...         ...  ...              ...              ...
999291    Female           4  ...  1. Not enrolled  1. Not enrolled
999406      Male           7  ...  1. Not enrolled  1. Not enrolled
999543    Female           8  ...  1. Not enrolled  1. Not enrolled
999698    Female           5  ...  1. Not enrolled  1. Not enrolled
999963    Female           9  ...  1. Not enrolled  1. Not enrolled

[8984 rows x 88 columns]
<class 'pandas.core.frame.DataFrame'>
Int64Index: 8984 entries, 100061 to 999963
Data columns (total 88 columns):
 #   Column                 Non-Null Count  Dtype  
---  ------                 --------------  -----  
 0   gender                 8984 non-null   object 
 1   birthmonth             8984 non-null   int64  
 2   birthyear              8984 non-null   int64  
 3   highestgradecompleted  6663 non-null   float64
 4   maritalstatus          6672 non-null   object 
 5   childathome            4791 non-null   float64
 6   childnotathome         4791 non-null   float64
 7   wageincome             5091 non-null   float64
 8   weeklyhrscomputer      6710 non-null   object 
 9   weeklyhrstv            6711 non-null   object 
 10  nightlyhrssleep        6706 non-null   float64
 11  satverbal              1406 non-null   float64
 12  satmath                1407 non-null   float64
 13  gpaoverall             6004 non-null   float64
 14  gpaenglish             5798 non-null   float64
 15  gpamath                5766 non-null   float64
 16  gpascience             5684 non-null   float64
 17  highestdegree          8953 non-null   object 
 18  govprovidejobs         1833 non-null   object 
 19  govpricecontrols       1859 non-null   object 
 20  govhealthcare          1874 non-null   object 
 21  govelderliving         1872 non-null   object 
 22  govindhelp             1815 non-null   object 
 23  govunemp               1811 non-null   object 
 24  govincomediff          1775 non-null   object 
 25  govcollegefinance      1875 non-null   object 
 26  govdecenthousing       1847 non-null   object 
 27  govprotectenvironment  1860 non-null   object 
 28  weeksworked00          8603 non-null   float64
 29  weeksworked01          8564 non-null   float64
 30  weeksworked02          8556 non-null   float64
 31  weeksworked03          8490 non-null   float64
 32  weeksworked04          8458 non-null   float64
 33  weeksworked05          8403 non-null   float64
 34  weeksworked06          8340 non-null   float64
 35  weeksworked07          8272 non-null   float64
 36  weeksworked08          8186 non-null   float64
 37  weeksworked09          8146 non-null   float64
 38  weeksworked10          8054 non-null   float64
 39  weeksworked11          7968 non-null   float64
 40  weeksworked12          7747 non-null   float64
 41  weeksworked13          7680 non-null   float64
 42  weeksworked14          7612 non-null   float64
 43  weeksworked15          7389 non-null   float64
 44  weeksworked16          7068 non-null   float64
 45  weeksworked17          6670 non-null   float64
 46  colenrfeb97            1250 non-null   object 
 47  colenroct97            8501 non-null   object 
 48  colenrfeb98            8501 non-null   object 
 49  colenroct98            8888 non-null   object 
 50  colenrfeb99            8865 non-null   object 
 51  colenroct99            8851 non-null   object 
 52  colenrfeb00            8820 non-null   object 
 53  colenroct00            8805 non-null   object 
 54  colenrfeb01            8786 non-null   object 
 55  colenroct01            8758 non-null   object 
 56  colenrfeb02            8732 non-null   object 
 57  colenroct02            8698 non-null   object 
 58  colenrfeb03            8658 non-null   object 
 59  colenroct03            8622 non-null   object 
 60  colenrfeb04            8578 non-null   object 
 61  colenroct04            8546 non-null   object 
 62  colenrfeb05            8508 non-null   object 
 63  colenroct05            8471 non-null   object 
 64  colenrfeb06            8426 non-null   object 
 65  colenroct06            8407 non-null   object 
 66  colenrfeb07            8352 non-null   object 
 67  colenroct07            8331 non-null   object 
 68  colenrfeb08            8289 non-null   object 
 69  colenroct08            8280 non-null   object 
 70  colenrfeb09            8236 non-null   object 
 71  colenroct09            8193 non-null   object 
 72  colenrfeb10            8116 non-null   object 
 73  colenroct10            8091 non-null   object 
 74  colenrfeb11            8037 non-null   object 
 75  colenroct11            7972 non-null   object 
 76  colenrfeb12            7794 non-null   object 
 77  colenroct12            7754 non-null   object 
 78  colenrfeb13            7754 non-null   object 
 79  colenroct13            7754 non-null   object 
 80  colenrfeb14            7624 non-null   object 
 81  colenroct14            7469 non-null   object 
 82  colenrfeb15            7469 non-null   object 
 83  colenroct15            7469 non-null   object 
 84  colenrfeb16            7036 non-null   object 
 85  colenroct16            6733 non-null   object 
 86  colenrfeb17            6733 non-null   object 
 87  colenroct17            6734 non-null   object 
dtypes: float64(29), int64(2), object(57)
memory usage: 6.1+ MB
None

STEP 6: ทำการเลือก row เริ่มที่แถว 1001 ไปถึงแถว 1004

Use slicing to select a few rows

[1000:1004] เนื่องจาก index เริ่มต้นที่ 0 => [เลขแถวเริ่มต้น-1: เลขแถวปลายทาง]

print(nls97[1000:1004]) #ให้ทดลองเปิดไฟล์ .csv ในโปรแกรม Excel จะอยู่ที่บรรทัด 1002 - 1005
gender  birthmonth  ...      colenrfeb17      colenroct17
personid                      ...                                  
195884      Male          12  ...              NaN              NaN
195891      Male           9  ...  1. Not enrolled  1. Not enrolled
195970    Female           3  ...  1. Not enrolled  1. Not enrolled
195996    Female           9  ...              NaN              NaN

[4 rows x 88 columns]

STEP 7: ทำการ Transport กลับ rows เป็น columns กลับ columns เป็น rows

ใช้คำสั่ง .T Transport เพื่อให้เห็นรายละเอียดของข้อมูลมากขึ้น

print(nls97[1000:1004].T)
personid              195884           195891           195970  195996
gender                  Male             Male           Female  Female
birthmonth                12                9                3       9
birthyear               1981             1980             1982    1980
highestgradecompleted    NaN               12               17     NaN
maritalstatus            NaN    Never-married    Never-married     NaN
...                      ...              ...              ...     ...
colenroct15              NaN  1. Not enrolled  1. Not enrolled     NaN
colenrfeb16              NaN  1. Not enrolled  1. Not enrolled     NaN
colenroct16              NaN  1. Not enrolled  1. Not enrolled     NaN
colenrfeb17              NaN  1. Not enrolled  1. Not enrolled     NaN
colenroct17              NaN  1. Not enrolled  1. Not enrolled     NaN

[88 rows x 4 columns]

STEP 8: ทำการเลือก rows แบบกระโดดข้ามแถวระหว่างทาง

Use slicing to start at the 1001st row and go to the 1004th row, skipping every other row.

ใช้คำสั่ง [เลขแถวเริ่มต้น-1 : เลขแถวปลายทาง : ช่วงแถวที่ข้าม]

print(nls97[1000:1004:2].T) #ข้ามไป step ละ 2 แถว เช่น 1 -> 3
personid              195884           195970
gender                  Male           Female
birthmonth                12                3
birthyear               1981             1982
highestgradecompleted    NaN               17
maritalstatus            NaN    Never-married
...                      ...              ...
colenroct15              NaN  1. Not enrolled
colenrfeb16              NaN  1. Not enrolled
colenroct16              NaN  1. Not enrolled
colenrfeb17              NaN  1. Not enrolled
colenroct17              NaN  1. Not enrolled

[88 rows x 2 columns]

STEP 9: ทำการเลือก 3 rows แรก ที่อยู่บนสุด

Select the first three rows using head and [ ] operator slicing

ใช้คำสั่ง [: n] n คือจำนวนแถวบนสุด ผลลัพธ์เหมือนกับคำสั่ง .head()

#select first 3 rows using head() and Python slicing
print(nls97.head(3).T)
print(nls97[:3].T) #ใช้ [: ] ผลลัพธ์เหมือนกับคำสั่ง .head()
personid                        100061           100139           100284
gender                          Female             Male             Male
birthmonth                           5                9               11
birthyear                         1980             1983             1984
highestgradecompleted               13               12                7
maritalstatus                  Married          Married    Never-married
...                                ...              ...              ...
colenroct15            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenrfeb16            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenroct16            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenrfeb17            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenroct17            1. Not enrolled  1. Not enrolled  1. Not enrolled

[88 rows x 3 columns]
personid                        100061           100139           100284
gender                          Female             Male             Male
birthmonth                           5                9               11
birthyear                         1980             1983             1984
highestgradecompleted               13               12                7
maritalstatus                  Married          Married    Never-married
...                                ...              ...              ...
colenroct15            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenrfeb16            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenroct16            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenrfeb17            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenroct17            1. Not enrolled  1. Not enrolled  1. Not enrolled

[88 rows x 3 columns]

STEP 10: ทำการเลือก 3 rows ล่างสุด

Select the last three rows using tail and [ ] operator slicing

ใช้คำสั่ง [-n: ] n คือ จำนวนแถวล่างสุด ผลลัพธ์เหมือนกับคำสั่ง .tail()

#select last 3 rows using tail() and Python slicing
print(nls97.tail(3).T)
print(nls97[-3:].T) #ใช้ [-n: ] ผลลัพธ์เหมือนกับคำสั่ง .tail()
personid                        999543           999698           999963
gender                          Female           Female           Female
birthmonth                           8                5                9
birthyear                         1984             1983             1982
highestgradecompleted               12               12               17
maritalstatus                 Divorced    Never-married          Married
...                                ...              ...              ...
colenroct15            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenrfeb16            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenroct16            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenrfeb17            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenroct17            1. Not enrolled  1. Not enrolled  1. Not enrolled

[88 rows x 3 columns]
personid                        999543           999698           999963
gender                          Female           Female           Female
birthmonth                           8                5                9
birthyear                         1984             1983             1982
highestgradecompleted               12               12               17
maritalstatus                 Divorced    Never-married          Married
...                                ...              ...              ...
colenroct15            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenrfeb16            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenroct16            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenrfeb17            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenroct17            1. Not enrolled  1. Not enrolled  1. Not enrolled

[88 rows x 3 columns]

STEP 11: ทำการเลือกค่าข้อมูล values ของ rows ด้วยคำสั่ง .loc

Select a few rows using the loc data accessor

ใช้คำสั่ง .loc[ index_values ] ในที่นี้คือค่าที่อยู่ในแถวของ personid ซึ่งตั้งเป็น index]

เช่น ต้องการค่าข้อมูลแถวของ personalid (เนื่องจากเป็น index) ที่ 195884, 195891, 195970

print(nls97.loc[[195884,195891,195970]].T) # , เลือกแบบค่าที่ต้องการ
personid              195884           195891           195970
gender                  Male             Male           Female
birthmonth                12                9                3
birthyear               1981             1980             1982
highestgradecompleted    NaN               12               17
maritalstatus            NaN    Never-married    Never-married
...                      ...              ...              ...
colenroct15              NaN  1. Not enrolled  1. Not enrolled
colenrfeb16              NaN  1. Not enrolled  1. Not enrolled
colenroct16              NaN  1. Not enrolled  1. Not enrolled
colenrfeb17              NaN  1. Not enrolled  1. Not enrolled
colenroct17              NaN  1. Not enrolled  1. Not enrolled

[88 rows x 3 columns]
print(nls97.loc[195884:195970].T) # : เลือกแบบจากเริ่มต้นถึงปลายทาง
personid              195884           195891           195970
gender                  Male             Male           Female
birthmonth                12                9                3
birthyear               1981             1980             1982
highestgradecompleted    NaN               12               17
maritalstatus            NaN    Never-married    Never-married
...                      ...              ...              ...
colenroct15              NaN  1. Not enrolled  1. Not enrolled
colenrfeb16              NaN  1. Not enrolled  1. Not enrolled
colenroct16              NaN  1. Not enrolled  1. Not enrolled
colenrfeb17              NaN  1. Not enrolled  1. Not enrolled
colenroct17              NaN  1. Not enrolled  1. Not enrolled

[88 rows x 3 columns]

STEP 12: ทำการเลือกแบบค่าตำแหน่ง index ของแถวเพื่อเข้าถึงค่าข้อมูล values ด้วยคำสั่ง .iloc

Select a few rows from the beginning of the DataFrame with the iloc data accessor

ใช้คำสั่ง .iloc[ index_numbers ] ในที่นี้คือค่าตำแหน่งแถวของ personid ซึ่งตั้งเป็น index]

print(nls97.iloc[[0,1,2]].T) #เข้าถึงแถวด้านบน นับจากบนลงล่าง
print(nls97.iloc[[-3,-2,-1]].T) #เข้าถึงแถวจากด้านล่าง -1 คืออยู่ล่างสุด นับจากล่างขึ้นบน
personid                        100061           100139           100284
gender                          Female             Male             Male
birthmonth                           5                9               11
birthyear                         1980             1983             1984
highestgradecompleted               13               12                7
maritalstatus                  Married          Married    Never-married
...                                ...              ...              ...
colenroct15            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenrfeb16            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenroct16            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenrfeb17            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenroct17            1. Not enrolled  1. Not enrolled  1. Not enrolled

[88 rows x 3 columns]
personid                        999543           999698           999963
gender                          Female           Female           Female
birthmonth                           8                5                9
birthyear                         1984             1983             1982
highestgradecompleted               12               12               17
maritalstatus                 Divorced    Never-married          Married
...                                ...              ...              ...
colenroct15            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenrfeb16            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenroct16            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenrfeb17            1. Not enrolled  1. Not enrolled  1. Not enrolled
colenroct17            1. Not enrolled  1. Not enrolled  1. Not enrolled

[88 rows x 3 columns]

STEP 13: ทำการเลือกหลาย rows ตามเงื่อนไขด้วย boolean indexing

Select multiple rows conditionally

โจทย์

สร้าง DataFrame ของบุคคลที่นอนหลับ ใช้ข้อมูลของคอลัมน์ nightlyhrssleep

โดยพิจาณาค่า Quantile ประมาณ 5% พบว่านอนหลับประมาณ 4 ชั่วโมง

ของผู้ตอบแบบสำรวจทั้งหมด 6,706 คน

ลองทดสอบว่าใครนอนหลับ 4 ชั่วโมงหรือน้อยกว่า

ด้วย nls97 nightlyhrssleep<=4

ซึ่งสร้างชุดค่า True (<=4) และ False (!<=4) ของ pandas ที่เรากำหนดให้กับ sleepcheckbool

print(nls97.nightlyhrssleep.quantile(0.05))  #ทดสอบใช้สถิติ quantile 5% พบว่าได้ 4 ชั่วโมง 
print(nls97.nightlyhrssleep.count())         #นับจำนวนผู้คอบแบบสำรวจทั้งหมดในคอลัมน์นี้ พบว่าได้ 6706 คน
sleepcheckbool = nls97.nightlyhrssleep<=4    #สร้างเงื่อนไข ว่าใครนอนหลับ 4 ชั่วโมงหรือน้อยกว่านั้น
print(sleepcheckbool)                        #แสดงคนที่นอนหลับ 4 ชั่วโมงหรือน้อยกว่านั้น
sleepcheckbool.to_csv("/content/sleepcheckbool") #ถ้า True แสดงว่านอนหลับ <= 4 ชั่วโมง
lowsleep = nls97.loc[sleepcheckbool] #ใช้ข้อมูล nls97 แล้ว Filter ข้อมูล sleepcheckbool(<=4)เก็บใน lowsleep
print(lowsleep.shape)                #ข้อมูลมี 364 rows 88 columns
lowsleep.to_csv("/content/lowsleep") #แสดงข้อมูล lowsleep ที่รวมข้อมูล nls97 โดย Filer sleepcheckbool
4.0
6706
personid
100061    False
100139    False
100284    False
100292    False
100583    False
          ...  
999291    False
999406    False
999543    False
999698    False
999963    False
Name: nightlyhrssleep, Length: 8984, dtype: bool
(364, 88)

STEP 14: ทำการเลือก rows ตามหลายเงื่อนไข

Select rows based on multiple conditions

ใช้คำสั่ง .describe() หาค่าสถิติเบื้องต้นของทุก colums ใน DataFrame

โจทย์

ผู้ที่นอนน้อยจะมีจำนวนบุตรที่บ้านอยู่กี่คน

ใช้ Python อธิบายเพื่อให้เข้าใจถึงการแจกแจงจำนวนบุตรของผู้ที่นอน <= 4 ชั่วโมง

สร้าง DataFrame ใหม่กับคนที่มี nightlyhrsleep <= 4 ชั่วโมง และมีจำนวนลูกที่บ้าน >= 3 คนขึ้นไป

print(lowsleep.childathome.describe())  #ในที่นี้เราจะดูของคอลัมน์ childathome ที่อยู่ภายในชุดข้อมูลของ lowsleep
lowsleep3pluschildren = nls97.loc[(nls97.nightlyhrssleep<=4) &amp; (nls97.childathome>=3)] #สร้างเงื่อนไขขึ้น
print(lowsleep3pluschildren.shape) #แสดงจำนวน rows และ colums
print(lowsleep3pluschildren)       #แสดงข้อมูล
lowsleep3pluschildren.to_csv("/content/lowsleep3pluschildren") #Export เป็นไฟล์เพิ่มนามสกุล .csv เปิด excel
count    293.000000
mean       1.788396
std        1.400685
min        0.000000
25%        1.000000
50%        2.000000
75%        3.000000
max        9.000000
Name: childathome, dtype: float64
(82, 88)
          gender  birthmonth  ...        colenrfeb17        colenroct17
personid                      ...                                      
119754    Female           6  ...    1. Not enrolled    1. Not enrolled
141531    Female          11  ...    1. Not enrolled    1. Not enrolled
152706      Male           7  ...    1. Not enrolled    1. Not enrolled
156823    Female          12  ...    1. Not enrolled    1. Not enrolled
158355    Female           7  ...    1. Not enrolled    1. Not enrolled
...          ...         ...  ...                ...                ...
905774      Male           6  ...    1. Not enrolled    1. Not enrolled
907315    Female           1  ...    1. Not enrolled    1. Not enrolled
955166      Male          12  ...    1. Not enrolled    1. Not enrolled
956100    Female          10  ...  3. 4-year college  3. 4-year college
991756      Male          11  ...    1. Not enrolled    1. Not enrolled

[82 rows x 88 columns]

STEP 15: เลือก rows และ columns ตามหลายเงื่อนไข

Select rows based on multiple conditions and also select columns

updatelowsleep3pluschildren = nls97.loc[(nls97.nightlyhrssleep<=4) &amp; (nls97.childathome>=3),
                                  ['nightlyhrssleep','childathome']]   #เลือกเฉพาะ Columns ที่ต้องการ
print(updatelowsleep3pluschildren)  #แสดงข้อมูล
updatelowsleep3pluschildren.to_csv("/content/updatelowsleep3pluschildren") #Export เป็นไฟล์.csv
 nightlyhrssleep  childathome
personid                              
119754                4.0          4.0
141531                4.0          5.0
152706                4.0          4.0
156823                1.0          3.0
158355                4.0          4.0
...                   ...          ...
905774                4.0          3.0
907315                4.0          3.0
955166                3.0          3.0
956100                4.0          6.0
991756                4.0          3.0

[82 rows x 2 columns]

Workshop 4: สร้างค่าความถี่ให้กับข้อมูล

–> Generating frequencies for categorical variables

Input Datasets

  • nls97.csv – the National Longitudinal Survey (NLS) 1997-2017.

Question 4: สิ่งที่เรากำลังหาอยู่ เราจะเห็นได้จากการกระจายตัวของความถี่ ดังนั้นเราจะสร้าง frequencies เพื่อทำให้ข้อมูลสามารถใช้ประโยชน์ได้ด้วยวิธีการใดบ้าง?

STEP 1: นำเข้า Datasets โดยทำการ Upload ไฟล์ nls97.csv ขึ้น Google Colab (ไฟล์นี้จะถูกลบเมื่อเราหลุดจาก Session หรือปิด Browser) หรือ Python IDE เช่น PyCharm, VSCode, Juputer Notebook, etc.

STEP 2: ทำการอ่านไฟล์ .csv ด้วย pandas เก็บเป็น Dataframe

ใช้คำสั่ง .read_csv()

STEP 3: ตั้งค่าและแสดง index และ size ของ nls97 data

ใช้คำสั่ง set_index()

STEP 4: ตั้งค่าและแสดง index และ size ของ nls97 data

ใช้คำสั่ง set_index()

STEP 5: แสดงจำนวน data types และ non-null value

ใช้คำสั่ง info()

import pandas as pd
import numpy as np
nls97 = pd.read_csv("/content/nls97.csv")
nls97.set_index("personid", inplace=True)
print(nls97)
print(nls97.info())
gender  birthmonth  ...      colenrfeb17      colenroct17
personid                      ...                                  
100061    Female           5  ...  1. Not enrolled  1. Not enrolled
100139      Male           9  ...  1. Not enrolled  1. Not enrolled
100284      Male          11  ...  1. Not enrolled  1. Not enrolled
100292      Male           4  ...              NaN              NaN
100583      Male           1  ...  1. Not enrolled  1. Not enrolled
...          ...         ...  ...              ...              ...
999291    Female           4  ...  1. Not enrolled  1. Not enrolled
999406      Male           7  ...  1. Not enrolled  1. Not enrolled
999543    Female           8  ...  1. Not enrolled  1. Not enrolled
999698    Female           5  ...  1. Not enrolled  1. Not enrolled
999963    Female           9  ...  1. Not enrolled  1. Not enrolled

[8984 rows x 88 columns]
<class 'pandas.core.frame.DataFrame'>
Int64Index: 8984 entries, 100061 to 999963
Data columns (total 88 columns):
 #   Column                 Non-Null Count  Dtype  
---  ------                 --------------  -----  
 0   gender                 8984 non-null   object 
 1   birthmonth             8984 non-null   int64  
 2   birthyear              8984 non-null   int64  
 3   highestgradecompleted  6663 non-null   float64
 4   maritalstatus          6672 non-null   object 
 5   childathome            4791 non-null   float64
 6   childnotathome         4791 non-null   float64
 7   wageincome             5091 non-null   float64
 8   weeklyhrscomputer      6710 non-null   object 
 9   weeklyhrstv            6711 non-null   object 
 10  nightlyhrssleep        6706 non-null   float64
 11  satverbal              1406 non-null   float64
 12  satmath                1407 non-null   float64
 13  gpaoverall             6004 non-null   float64
 14  gpaenglish             5798 non-null   float64
 15  gpamath                5766 non-null   float64
 16  gpascience             5684 non-null   float64
 17  highestdegree          8953 non-null   object 
 18  govprovidejobs         1833 non-null   object 
 19  govpricecontrols       1859 non-null   object 
 20  govhealthcare          1874 non-null   object 
 21  govelderliving         1872 non-null   object 
 22  govindhelp             1815 non-null   object 
 23  govunemp               1811 non-null   object 
 24  govincomediff          1775 non-null   object 
 25  govcollegefinance      1875 non-null   object 
 26  govdecenthousing       1847 non-null   object 
 27  govprotectenvironment  1860 non-null   object 
 28  weeksworked00          8603 non-null   float64
 29  weeksworked01          8564 non-null   float64
 30  weeksworked02          8556 non-null   float64
 31  weeksworked03          8490 non-null   float64
 32  weeksworked04          8458 non-null   float64
 33  weeksworked05          8403 non-null   float64
 34  weeksworked06          8340 non-null   float64
 35  weeksworked07          8272 non-null   float64
 36  weeksworked08          8186 non-null   float64
 37  weeksworked09          8146 non-null   float64
 38  weeksworked10          8054 non-null   float64
 39  weeksworked11          7968 non-null   float64
 40  weeksworked12          7747 non-null   float64
 41  weeksworked13          7680 non-null   float64
 42  weeksworked14          7612 non-null   float64
 43  weeksworked15          7389 non-null   float64
 44  weeksworked16          7068 non-null   float64
 45  weeksworked17          6670 non-null   float64
 46  colenrfeb97            1250 non-null   object 
 47  colenroct97            8501 non-null   object 
 48  colenrfeb98            8501 non-null   object 
 49  colenroct98            8888 non-null   object 
 50  colenrfeb99            8865 non-null   object 
 51  colenroct99            8851 non-null   object 
 52  colenrfeb00            8820 non-null   object 
 53  colenroct00            8805 non-null   object 
 54  colenrfeb01            8786 non-null   object 
 55  colenroct01            8758 non-null   object 
 56  colenrfeb02            8732 non-null   object 
 57  colenroct02            8698 non-null   object 
 58  colenrfeb03            8658 non-null   object 
 59  colenroct03            8622 non-null   object 
 60  colenrfeb04            8578 non-null   object 
 61  colenroct04            8546 non-null   object 
 62  colenrfeb05            8508 non-null   object 
 63  colenroct05            8471 non-null   object 
 64  colenrfeb06            8426 non-null   object 
 65  colenroct06            8407 non-null   object 
 66  colenrfeb07            8352 non-null   object 
 67  colenroct07            8331 non-null   object 
 68  colenrfeb08            8289 non-null   object 
 69  colenroct08            8280 non-null   object 
 70  colenrfeb09            8236 non-null   object 
 71  colenroct09            8193 non-null   object 
 72  colenrfeb10            8116 non-null   object 
 73  colenroct10            8091 non-null   object 
 74  colenrfeb11            8037 non-null   object 
 75  colenroct11            7972 non-null   object 
 76  colenrfeb12            7794 non-null   object 
 77  colenroct12            7754 non-null   object 
 78  colenrfeb13            7754 non-null   object 
 79  colenroct13            7754 non-null   object 
 80  colenrfeb14            7624 non-null   object 
 81  colenroct14            7469 non-null   object 
 82  colenrfeb15            7469 non-null   object 
 83  colenroct15            7469 non-null   object 
 84  colenrfeb16            7036 non-null   object 
 85  colenroct16            6733 non-null   object 
 86  colenrfeb17            6733 non-null   object 
 87  colenroct17            6734 non-null   object 
dtypes: float64(29), int64(2), object(57)
memory usage: 6.1+ MB
None

STEP 6: แปลง data types ของ columns ที่เป็น object ให้เป็น category เพื่อทำข้อมูลให้เหมาะสม

data typs –> category เหมาะสำหรับข้อมูลที่มีซ้ำ ๆ กัน ที่ไม่ค่อยต่างกันมาก ช่วยในการเรื่องการประหยัด Memory

ใช้คำสั่ง .loc[ ] ทำการ Filter เข้าถึงข้อมูล –> คำสั่ง pandas หมวด Filter จะมีทั้ง .loc [ ], .iloc [ ], .query [ ]

ใช้คำสั่ง .select_dtypes ทำการเลือก data types

ใช้คำสั่ง .apply(lamba function) เพื่อแปลงข้อมูล

ใช้คำสั่ง .astype ทำการแปลง data types

nls97.loc[:, nls97.dtypes == 'object'] = \
  nls97.select_dtypes(['object']). \
  apply(lambda x: x.astype('category'))  
print(nls97.info())                         
#เครื่องหมาย \ คือ เพื่อเชื่อมประโยคให้ต่อกันในอีกบรรทัดนึง
#Syntax --> .loc['row_name' , 'column_name'] สนใจชื่อ
#Syntax --> .iloc['row_index_number' , 'column_index_number'] สนใจตำแหน่ง index ของ row และ column
#loc[: Filter ชื่อทุกตัว, ที่มีเงื่อนไขเป็น 'object'] และทำการเลือก loc ย่อมาจาก location based
#ทำการแปลง colums ที่เป็น 'object' --> 'category'
#ผลปรากฎว่า 'category' ช่วยลด memory (2.7 MB) ได้มากกว่า 'object' (6.1+ MB)
<class 'pandas.core.frame.DataFrame'>
Int64Index: 8984 entries, 100061 to 999963
Data columns (total 88 columns):
 #   Column                 Non-Null Count  Dtype   
---  ------                 --------------  -----   
 0   gender                 8984 non-null   category
 1   birthmonth             8984 non-null   int64   
 2   birthyear              8984 non-null   int64   
 3   highestgradecompleted  6663 non-null   float64 
 4   maritalstatus          6672 non-null   category
 5   childathome            4791 non-null   float64 
 6   childnotathome         4791 non-null   float64 
 7   wageincome             5091 non-null   float64 
 8   weeklyhrscomputer      6710 non-null   category
 9   weeklyhrstv            6711 non-null   category
 10  nightlyhrssleep        6706 non-null   float64 
 11  satverbal              1406 non-null   float64 
 12  satmath                1407 non-null   float64 
 13  gpaoverall             6004 non-null   float64 
 14  gpaenglish             5798 non-null   float64 
 15  gpamath                5766 non-null   float64 
 16  gpascience             5684 non-null   float64 
 17  highestdegree          8953 non-null   category
 18  govprovidejobs         1833 non-null   category
 19  govpricecontrols       1859 non-null   category
 20  govhealthcare          1874 non-null   category
 21  govelderliving         1872 non-null   category
 22  govindhelp             1815 non-null   category
 23  govunemp               1811 non-null   category
 24  govincomediff          1775 non-null   category
 25  govcollegefinance      1875 non-null   category
 26  govdecenthousing       1847 non-null   category
 27  govprotectenvironment  1860 non-null   category
 28  weeksworked00          8603 non-null   float64 
 29  weeksworked01          8564 non-null   float64 
 30  weeksworked02          8556 non-null   float64 
 31  weeksworked03          8490 non-null   float64 
 32  weeksworked04          8458 non-null   float64 
 33  weeksworked05          8403 non-null   float64 
 34  weeksworked06          8340 non-null   float64 
 35  weeksworked07          8272 non-null   float64 
 36  weeksworked08          8186 non-null   float64 
 37  weeksworked09          8146 non-null   float64 
 38  weeksworked10          8054 non-null   float64 
 39  weeksworked11          7968 non-null   float64 
 40  weeksworked12          7747 non-null   float64 
 41  weeksworked13          7680 non-null   float64 
 42  weeksworked14          7612 non-null   float64 
 43  weeksworked15          7389 non-null   float64 
 44  weeksworked16          7068 non-null   float64 
 45  weeksworked17          6670 non-null   float64 
 46  colenrfeb97            1250 non-null   category
 47  colenroct97            8501 non-null   category
 48  colenrfeb98            8501 non-null   category
 49  colenroct98            8888 non-null   category
 50  colenrfeb99            8865 non-null   category
 51  colenroct99            8851 non-null   category
 52  colenrfeb00            8820 non-null   category
 53  colenroct00            8805 non-null   category
 54  colenrfeb01            8786 non-null   category
 55  colenroct01            8758 non-null   category
 56  colenrfeb02            8732 non-null   category
 57  colenroct02            8698 non-null   category
 58  colenrfeb03            8658 non-null   category
 59  colenroct03            8622 non-null   category
 60  colenrfeb04            8578 non-null   category
 61  colenroct04            8546 non-null   category
 62  colenrfeb05            8508 non-null   category
 63  colenroct05            8471 non-null   category
 64  colenrfeb06            8426 non-null   category
 65  colenroct06            8407 non-null   category
 66  colenrfeb07            8352 non-null   category
 67  colenroct07            8331 non-null   category
 68  colenrfeb08            8289 non-null   category
 69  colenroct08            8280 non-null   category
 70  colenrfeb09            8236 non-null   category
 71  colenroct09            8193 non-null   category
 72  colenrfeb10            8116 non-null   category
 73  colenroct10            8091 non-null   category
 74  colenrfeb11            8037 non-null   category
 75  colenroct11            7972 non-null   category
 76  colenrfeb12            7794 non-null   category
 77  colenroct12            7754 non-null   category
 78  colenrfeb13            7754 non-null   category
 79  colenroct13            7754 non-null   category
 80  colenrfeb14            7624 non-null   category
 81  colenroct14            7469 non-null   category
 82  colenrfeb15            7469 non-null   category
 83  colenroct15            7469 non-null   category
 84  colenrfeb16            7036 non-null   category
 85  colenroct16            6733 non-null   category
 86  colenrfeb17            6733 non-null   category
 87  colenroct17            6734 non-null   category
dtypes: category(57), float64(29), int64(2)
memory usage: 2.7 MB
None

STEP 7: แสดงชื่อ columns ที่มีชนิดข้อมูล category และตรวจสอบจำนวน missing values

ใช้คำสั่ง select_dtypes(include=[ “category” ]) เลือกเฉพาะ data types ชนิด category

ใช้คำสั่ง .isnull().sum() หาผลรวมของ missing values

–> สังเกตเห็นว่า

gender = 0 แสดงว่าไม่มี missing values ถือว่าเป็น complete values

highestdegree = 31 คือค่า missing values ที่พบก็ถือว่ายังน้อยกว่า columns อื่น ๆ

maritalstatus = 2312 คือค่า missing values ถือว่ามากแล้ว

catcols = nls97.select_dtypes(include=["category"]).columns
print(catcols)
print(nls97[catcols].isnull().sum())
Index(['gender', 'maritalstatus', 'weeklyhrscomputer', 'weeklyhrstv',
       'highestdegree', 'govprovidejobs', 'govpricecontrols', 'govhealthcare',
       'govelderliving', 'govindhelp', 'govunemp', 'govincomediff',
       'govcollegefinance', 'govdecenthousing', 'govprotectenvironment',
       'colenrfeb97', 'colenroct97', 'colenrfeb98', 'colenroct98',
       'colenrfeb99', 'colenroct99', 'colenrfeb00', 'colenroct00',
       'colenrfeb01', 'colenroct01', 'colenrfeb02', 'colenroct02',
       'colenrfeb03', 'colenroct03', 'colenrfeb04', 'colenroct04',
       'colenrfeb05', 'colenroct05', 'colenrfeb06', 'colenroct06',
       'colenrfeb07', 'colenroct07', 'colenrfeb08', 'colenroct08',
       'colenrfeb09', 'colenroct09', 'colenrfeb10', 'colenroct10',
       'colenrfeb11', 'colenroct11', 'colenrfeb12', 'colenroct12',
       'colenrfeb13', 'colenroct13', 'colenrfeb14', 'colenroct14',
       'colenrfeb15', 'colenroct15', 'colenrfeb16', 'colenroct16',
       'colenrfeb17', 'colenroct17'],
      dtype='object')
gender                      0
maritalstatus            2312
weeklyhrscomputer        2274
weeklyhrstv              2273
highestdegree              31
govprovidejobs           7151
govpricecontrols         7125
govhealthcare            7110
govelderliving           7112
govindhelp               7169
govunemp                 7173
govincomediff            7209
govcollegefinance        7109
govdecenthousing         7137
govprotectenvironment    7124
colenrfeb97              7734
colenroct97               483
colenrfeb98               483
colenroct98                96
colenrfeb99               119
colenroct99               133
colenrfeb00               164
colenroct00               179
colenrfeb01               198
colenroct01               226
colenrfeb02               252
colenroct02               286
colenrfeb03               326
colenroct03               362
colenrfeb04               406
colenroct04               438
colenrfeb05               476
colenroct05               513
colenrfeb06               558
colenroct06               577
colenrfeb07               632
colenroct07               653
colenrfeb08               695
colenroct08               704
colenrfeb09               748
colenroct09               791
colenrfeb10               868
colenroct10               893
colenrfeb11               947
colenroct11              1012
colenrfeb12              1190
colenroct12              1230
colenrfeb13              1230
colenroct13              1230
colenrfeb14              1360
colenroct14              1515
colenrfeb15              1515
colenroct15              1515
colenrfeb16              1948
colenroct16              2251
colenrfeb17              2251
colenroct17              2250
dtype: int64

STEP 8: ทำการแสดง frequencies ของสถานะสมรส maritalstatus

ใช้คำสั่ง .value_counts() ทำการนับจำนวน values

print(nls97.maritalstatus.value_counts())
Married          3066
Never-married    2766
Divorced          663
Separated         154
Widowed            23
Name: maritalstatus, dtype: int64

STEP 9: ทำการปิดการเรียงตามจำนวน frequency ซึ่งจะเรียงเป็นตัวอักษรแทน

Turn off sorting by frequency

ใช้คำสั่ง (sort=False)

print(nls97.maritalstatus.value_counts(sort=False)) #เปลี่ยนเป็น True จะเรียงตามจำนวนความถี่
Divorced         0.099371
Married          0.459532
Never-married    0.414568
Separated        0.023082
Widowed          0.003447
Name: maritalstatus, dtype: float64

STEP 11: แสดง % frequency ของคอลัมน์ government ทั้งหมด

Filter the DataFrame for just the government responsibility columns, then use apply to run value_counts on all columns in that DataFrame

ใช้คำสั่ง .filter(like=”text”) เพื่อกรองคำที่อยู่ใน columns ที่ต้องการ

ใช้คำสั่ง .apply ทำการปรับค่ารูปแบบข้อมูลตามที่ใส่ไว้

print(nls97.filter(like="gov").apply(pd.value_counts,normalize=True))
 govprovidejobs  ...  govprotectenvironment
1. Definitely            0.247681  ...               0.668817
2. Probably              0.336607  ...               0.286559
3. Probably not          0.252046  ...               0.029570
4. Definitely not        0.163666  ...               0.015054

[4 rows x 10 columns]

STEP 12: ค้นหา % frequency ของคอลัมน์ government ทั้งหมดที่แต่งงานแล้ว สถานะ Married

print(nls97[nls97.maritalstatus=="Married"].\
  filter(like="gov").\
  apply(pd.value_counts, normalize=True))
 govprovidejobs  ...  govprotectenvironment
1. Definitely            0.173315  ...               0.644505
2. Probably              0.328748  ...               0.313433
3. Probably not          0.314993  ...               0.028494
4. Definitely not        0.182944  ...               0.013569

[4 rows x 10 columns]

STEP 13: ค้นหา frequency และ % สำหรับ category columns ทั้งหมดใน DataFrame

ใช้คำสั่ง open(‘/path/…’,’w’) เพื่อสร้างไฟล์ว่างเปล่าชื่อ frequencies.txt รอโปรแกรมสร้างประมาณ 1 นาที

freqout = open('/content/frequencies.txt', 'w') #รอโปรแกรมสร้างให้

STEP 14: เขียนโปรแกรมแสดงค่า frequency ต่าง ๆ ของที่เป็น category columns ทั้งหมด

for col in nls97.select_dtypes(include=["category"]):
    print(col, "----------------------", "frequencies",
    nls97[col].value_counts(sort=False),"percentages",
    nls97[col].value_counts(normalize=True,sort=False),
    sep="\n\n", end="\n\n\n", file=freqout)
freqout.close() #Run เพียงครั้งเดียว

Workshop 5: การสร้าง Summary Statistics สำหรับ Continuous Variables

–> Generating summary statistics for continuous variables

Input Datasets

Question 5: เราจะสำรวจวิธีการเลือกและจัดระเบียบให้กับคอลัมน์ได้อย่างไร?

STEP 1: นำเข้า Datasets โดยทำการ Upload covidtotals.csv ขึ้น Google Colab (ไฟล์นี้จะถูกลบเมื่อเราหลุดจาก Session หรือปิด Browser) หรือ Python IDE เช่น PyCharm, VSCode, Juputer Notebook, etc.

STEP 2: นำเข้า pandas, numpy และ matplotlib libraries

STEP 3: ทำการอ่านไฟล์ .csv ด้วย pandas เก็บเป็น Dataframe และตั้งคอลัมน์ ‘lastdate’ เป็น datetime data type

ใช้คำสั่ง .read_csv() และ parse_dates=[ ‘lastdate’ ]

STEP 4: ตั้งค่าและแสดง index และ size ของ nls97 data

ใช้คำสั่ง set_index()

STEP 5: แสดงจำนวน data types และ non-null value

ใช้คำสั่ง info()

STEP 6: แสดงจำนวน rows และ columns

ใช้คำสั่ง .shape

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt #เพิ่ม matplotlib เข้ามาใช้สร้าง data visualization
covidtotals = pd.read_csv("/content/covidtotals.csv", parse_dates=['lastdate'])
covidtotals.set_index("iso_code", inplace=True)
print(covidtotals)
print(covidtotals.info())
print(covidtotals.shape)
#คำสั่ง parse_dates จะทำการแปลง Column 'lastdate' ให้เป็น Datetime Type วันเดือนปี เพื่อให้สามารถนำไปเปรียบเทียบช่วงเวลาได้
 lastdate        location  ...  gdp_per_capita  hosp_beds
iso_code                             ...                           
AFG      2020-06-01     Afghanistan  ...        1803.987       0.50
ALB      2020-06-01         Albania  ...       11803.431       2.89
DZA      2020-06-01         Algeria  ...       13913.839       1.90
AND      2020-06-01         Andorra  ...             NaN        NaN
AGO      2020-06-01          Angola  ...        5819.495        NaN
...             ...             ...  ...             ...        ...
VNM      2020-06-01         Vietnam  ...        6171.884       2.60
ESH      2020-06-01  Western Sahara  ...             NaN        NaN
YEM      2020-06-01           Yemen  ...        1479.147       0.70
ZMB      2020-06-01          Zambia  ...        3689.251       2.00
ZWE      2020-06-01        Zimbabwe  ...        1899.775       1.70

[210 rows x 11 columns]
<class 'pandas.core.frame.DataFrame'>
Index: 210 entries, AFG to ZWE
Data columns (total 11 columns):
 #   Column           Non-Null Count  Dtype         
---  ------           --------------  -----         
 0   lastdate         210 non-null    datetime64[ns]
 1   location         210 non-null    object        
 2   total_cases      210 non-null    int64         
 3   total_deaths     210 non-null    int64         
 4   total_cases_pm   209 non-null    float64       
 5   total_deaths_pm  209 non-null    float64       
 6   population       210 non-null    float64       
 7   pop_density      198 non-null    float64       
 8   median_age       186 non-null    float64       
 9   gdp_per_capita   182 non-null    float64       
 10  hosp_beds        164 non-null    float64       
dtypes: datetime64[ns](1), float64(7), int64(2), object(1)
memory usage: 19.7+ KB
None
(210, 11)

STEP 7: ทบทวนคำสั่ง ทดลองทำการสุ่มข้อมูล ปรับแต่ง และแสดง data types

look at a few rows of the covid cases data

ใช้คำสั่ง .sample(), .T, .dtypes

print(covidtotals.sample(2, random_state=1))
print(covidtotals.sample(2, random_state=1).T)
print(covidtotals.dtypes)
  lastdate  location  ...  gdp_per_capita  hosp_beds
iso_code                       ...                           
COG      2020-06-01     Congo  ...        4881.406        NaN
THA      2020-06-01  Thailand  ...       16277.671        2.1

[2 rows x 11 columns]
iso_code                         COG                  THA
lastdate         2020-06-01 00:00:00  2020-06-01 00:00:00
location                       Congo             Thailand
total_cases                      611                 3081
total_deaths                      20                   57
total_cases_pm               110.727                44.14
total_deaths_pm                3.624                0.817
population               5.51809e+06             6.98e+07
pop_density                   15.405              135.132
median_age                        19                 40.1
gdp_per_capita               4881.41              16277.7
hosp_beds                        NaN                  2.1
lastdate           datetime64[ns]
location                   object
total_cases                 int64
total_deaths                int64
total_cases_pm            float64
total_deaths_pm           float64
population                float64
pop_density               float64
median_age                float64
gdp_per_capita            float64
hosp_beds                 float64
dtype: object

STEP 8: แสดงข้อมูล Descriptive Statistics และข้อมูลสะสม Cumulative Values

Get descriptive statistics on the cumulative values

ใช้คำสั่ง .describe()

print(covidtotals.describe())
 total_cases   total_deaths  ...  gdp_per_capita   hosp_beds
count  2.100000e+02     210.000000  ...      182.000000  164.000000
mean   2.921614e+04    1770.714286  ...    19539.154588    3.012671
std    1.363978e+05    8705.565857  ...    19862.354091    2.464917
min    0.000000e+00       0.000000  ...      661.240000    0.100000
25%    1.757500e+02       4.000000  ...     4485.329000    1.300000
50%    1.242500e+03      25.500000  ...    13183.081500    2.358500
75%    1.011700e+04     241.250000  ...    28556.527250    3.895750
max    1.790191e+06  104383.000000  ...   116935.600000   13.800000

[8 rows x 9 columns]

STEP 9: แสดงค่าการกระจายตัวของข้อมูล

ใช้คำสั่ง np.arrange( ) –> numpy.arange(start, stop, step, dtype) ระยะห่างของข้อมูล

totvars = ['location','total_cases','total_deaths','total_cases_pm','total_deaths_pm']
print(covidtotals[totvars].quantile(np.arange(0.0, 1.1, 0.1)))
 total_cases  total_deaths  total_cases_pm  total_deaths_pm
0.0          0.0           0.0          0.8940           0.0000
0.1         22.9           0.0         18.4870           0.0000
0.2        105.2           2.0         56.7386           0.4008
0.3        302.0           6.7        118.2282           1.7348
0.4        762.0          12.0        214.9182           3.9734
0.5       1242.5          25.5        281.9970           6.2140
0.6       2514.6          54.6        546.0534          12.5644
0.7       6959.8         137.2       1074.0324          26.0638
0.8      16847.2         323.2       2208.7374          50.2896
0.9      46513.1        1616.9       3771.9956         139.5290
1.0    1790191.0      104383.0      19771.3480        1237.5510

STEP 10: แสดงการกระจายตัวของข้อมูล

View the distribution of total cases

ใช้คำสั่งของ matplotlib .hist สร้างภาพข้อมูล histogram

สังเกตอะไรได้ในชุดข้อมูลนี้ ข้อมูล 01/06/2020

จำนวนประเทศส่วนใหญ่มี covid cases < 200,000 กราฟกระจายสูงขึ้นไปทางขวา

และประเทศส่วนน้อยที่มี covid cases > 200,000 กราฟจะกระจายตัวไปทางซ้าย

plt.hist(covidtotals['total_cases']/1000, bins=12)
plt.title("Total Covid Cases (in thousands)")
plt.xlabel('Cases')
plt.ylabel("Number of Countries")
plt.show()

Practice 2: การจัดการค่าที่หายไป การลบข้อมูลแถวที่ซ้ำกัน และการจัดระเบียบข้อมูลตามกลุ่ม

Managing Missing Values, Removing Duplicated Rows, and Organizing using Groupby

Python Pandas Cheat Sheets

Workshop 6: ตรวจหาค่าที่หายไป ใส่ค่าข้อมูลใหม่ และลบแถวของข้อมูลที่หายไป

–> Finding, Inserting missing values and Deleting rows of missing values

Input Datasets

Question 6: เราจะตรวจหาข้อมูลที่หายไปแล้วทำการใส่ค่าเพื่อแก้ไขข้อมูลได้อย่างไร?

STEP 1: นำเข้า Datasets โดยทำการ Upload ไฟล์ covidtotalswithmissings.csv ขึ้น Google Colab (ไฟล์นี้จะถูกลบเมื่อเราหลุดจาก Session หรือปิด Browser) หรือ Python IDE เช่น PyCharm, VSCode, Juputer Notebook, etc.

STEP 2: นำเข้า pandas และ numpy libraries มาใช้งาน

STEP 3: ทำการอ่านไฟล์ .csv ด้วย pandas เก็บเป็น Dataframe

ใช้คำสั่ง .read_csv()

#import pandas and numpy
import pandas as pd
import numpy as np
covidtotals = pd.read_csv("/content/covidtotalswithmissings.csv")
print(covidtotals)
 iso_code    lastdate        location  ...  median_age  gdp_per_capita  hosp_beds
0        AFG  2020-06-01     Afghanistan  ...        18.6        1803.987       0.50
1        ALB  2020-06-01         Albania  ...        38.0       11803.431       2.89
2        DZA  2020-06-01         Algeria  ...        29.1       13913.839       1.90
3        AND  2020-06-01         Andorra  ...         NaN             NaN        NaN
4        AGO  2020-06-01          Angola  ...        16.8        5819.495        NaN
..       ...         ...             ...  ...         ...             ...        ...
205      VNM  2020-06-01         Vietnam  ...        32.6        6171.884       2.60
206      ESH  2020-06-01  Western Sahara  ...        28.4             NaN        NaN
207      YEM  2020-06-01           Yemen  ...        20.3        1479.147       0.70
208      ZMB  2020-06-01          Zambia  ...        17.7        3689.251       2.00
209      ZWE  2020-06-01        Zimbabwe  ...        19.6        1899.775       1.70

[210 rows x 12 columns]

STEP 4: ตั้งค่าและแสดง index และ size ของ covidtotalsmissings data

ใช้คำสั่ง set_index() ให้คอลัมน์ “iso_code” เป็นคอลัมน์ index

#set up the cumulative and demographic columns กดแค่ครั้งเดียว 
covidtotals.set_index("iso_code", inplace=True) #ย้อนกลับไปให้ใช้ reset_index()
print(covidtotals)
   lastdate        location  ...  gdp_per_capita  hosp_beds
iso_code                              ...                           
AFG       2020-06-01     Afghanistan  ...        1803.987       0.50
ALB       2020-06-01         Albania  ...       11803.431       2.89
DZA       2020-06-01         Algeria  ...       13913.839       1.90
AND       2020-06-01         Andorra  ...             NaN        NaN
AGO       2020-06-01          Angola  ...        5819.495        NaN
...              ...             ...  ...             ...        ...
VNM       2020-06-01         Vietnam  ...        6171.884       2.60
ESH       2020-06-01  Western Sahara  ...             NaN        NaN
YEM       2020-06-01           Yemen  ...        1479.147       0.70
ZMB       2020-06-01          Zambia  ...        3689.251       2.00
ZWE       2020-06-01        Zimbabwe  ...        1899.775       1.70

[210 rows x 11 columns]

STEP 5: ตั้งค่าคอลัมน์ข้อมูลสะสม Cumulatice และคอลัมน์ข้อมูลประชากรศาสตร์ Demographic

#set up the cumulative and demographic columns
totvars = ['location','total_cases','total_deaths','total_cases_pm',
  'total_deaths_pm']
demovars = ['population','pop_density','median_age','gdp_per_capita',
  'hosp_beds']
print(totvars)
print(demovars)
['location', 'total_cases', 'total_deaths', 'total_cases_pm', 'total_deaths_pm']
['population', 'pop_density', 'median_age', 'gdp_per_capita', 'hosp_beds']

STEP 6: เช็คค่า missing data ที่หายไปของคอลัมน์กลุ่ม demographic

Check the demographic columns for missing data.

(1) ใช้คำสั่ง .isnull().sum(axis=0)

  • 0 คือ เช็คหัว Columns ทำการนับจำนวน missing data
  • พบว่า population = 0 แสดงว่าไม่พบค่า missing data เป็น compltete data
  • พบว่าข้อมูล hosp_beds = 46 ประเทศ พบค่า missing data คิดเป็นประมาณ 20% จากทั้งหมด 210 ประเทศ

(2) ใช้คำสั่ง .isnull().sum(axis=1)

  • 1 คือ เช็ค Rows ของ Index ทำการนับจำนวน missing data พบว่า AND มี missing data 3 ค่า

(3) ใช้คำสั่ง .value_counts() นับค่าจำนวน missing data ที่พบของ demovarmisscnt

  • พบว่ามี 156 ประเทศ ข้อมูลครบสมบูรณ์ complete values
  • พบว่า 24 ประเทศ มีข้อมูลหายไป 1 ค่า (missing data)
  • 12 ประเทศ มีข้อมูลหายไป 2 ค่า 10 ประเทศ มีข้อมูลหายไป 3 ค่า และ 8 ประเทศ มีข้อมูลหายไป 8 ค่า
#check the demographic columns for missing
print(covidtotals[demovars].isnull().sum(axis=0))  #แสดง missing data ของ columns
demovarsmisscnt = covidtotals[demovars].isnull().sum(axis=1) #แสดง missing data ของ index rows
print() #ขึ้นบรรทัดใหม่
print(demovarsmisscnt)
print()
print(demovarsmisscnt.value_counts())
population         0
pop_density       12
median_age        24
gdp_per_capita    28
hosp_beds         46
dtype: int64

iso_code
AFG    0
ALB    0
DZA    0
AND    3
AGO    1
      ..
VNM    0
ESH    3
YEM    0
ZMB    0
ZWE    0
Length: 210, dtype: int64

0    156
1     24
2     12
3     10
4      8
dtype: int64

STEP 7: สร้างเงื่อนไขแสดงเฉพาะประเทศที่มีค่าที่หายไป หรือ missing data ตั้งแต่ 3 ค่าขึ้นไป

List the countries with three or more missing values for the demographic data

ใช้คำสั่ง .loc[ rows, columns ] ทำการ Filter เลือกแถวและคอลัมน์ที่ต้องการ

#check the demographic columns for missing --> condition >= 3
print(covidtotals.loc[demovarsmisscnt>=3, ['location'] + demovars].head(5)) #ลองใส่ 18 (10 + 8)
         location  ...  hosp_beds
iso_code                                   ...           
AND                               Andorra  ...        NaN
AIA                              Anguilla  ...        NaN
BES       Bonaire Sint Eustatius and Saba  ...        NaN
VGB                British Virgin Islands  ...        NaN
FRO                        Faeroe Islands  ...        NaN

[5 rows x 6 columns]
print(covidtotals.loc[demovarsmisscnt>=3, ['location'] + demovars].head(5).T) #Transpost
type(demovarsmisscnt)
iso_code            AND       AIA  ...                     VGB             FRO
location        Andorra  Anguilla  ...  British Virgin Islands  Faeroe Islands
population        77265     15002  ...                   30237           48865
pop_density     163.755       NaN  ...                 207.973          35.308
median_age          NaN       NaN  ...                     NaN             NaN
gdp_per_capita      NaN       NaN  ...                     NaN             NaN
hosp_beds           NaN       NaN  ...                     NaN             NaN

[6 rows x 5 columns]
pandas.core.series.Series

STEP 8: ตรวจ Covid case data ของค่าที่หายไป

Check the Covid case data for missing values

(1) ใช้คำสั่ง .isnull().sum(axis=0)

  • 0 คือ เช็คหัว Columns ทำการนับจำนวน missing data

(2) ใช้คำสั่ง .isnull().sum(axis=1)

  • 1 คือ เช็ค Rows ของ Index ทำการนับจำนวน missing data

(3) ใช้คำสั่ง .value_counts() นับค่าจำนวน missing data ที่พบของ totvarsmisscnt

  • location, total_cases, totol_deaths = 0 คือไม่พบ missing data แสดงว่าข้อมูลครบ complete data
  • พบว่ามี 2 columns คือ total_cases_pm, total_deaths_pm ที่มีค่า missing data คอลัมน์ละ 1 ค่า
#check the cumulative columns for missing
print(covidtotals[totvars].isnull().sum(axis=0)) #แสดง columns จำนวน missing data
totvarsmisscnt = covidtotals[totvars].isnull().sum(axis=1) #แสดง index rows จำนวน missing data
print()
print(totvarsmisscnt)
print()
print(totvarsmisscnt.value_counts()) #นับจำนวนค่า missing data ที่พบของ totvarsmisscnt
location           0
total_cases        0
total_deaths       0
total_cases_pm     1
total_deaths_pm    1
dtype: int64

iso_code
AFG    0
ALB    0
DZA    0
AND    0
AGO    0
      ..
VNM    0
ESH    0
YEM    0
ZMB    0
ZWE    0
Length: 210, dtype: int64

0    209
2      1
dtype: int64
#เงื่อนไข >0 นับจำนวน missing data ทั้งหมด เพื่อต้องการหาประเทศที่มี missing data (มีหายไป 2 ค่า 1 ประเทศ)
print(covidtotals.loc[totvarsmisscnt>0])  #ประเทศนั้นคือ HKG
   lastdate   location  ...  gdp_per_capita  hosp_beds
iso_code                         ...                           
HKG       2020-05-26  Hong Kong  ...        56054.92        NaN

[1 rows x 11 columns]
#แสดงรายละเอียดให้มากขึ้นใช้ Transpost
print(covidtotals.loc[totvarsmisscnt>0].T) 
#สังเกตว่ามี total_cases_pm และ total_deaths_pm มีค่าเท่ากับ Nan
iso_code                 HKG
lastdate          2020-05-26
location           Hong Kong
total_cases                0
total_deaths               0
total_cases_pm           NaN
total_deaths_pm          NaN
population       7.49699e+06
pop_density          7039.71
median_age              44.8
gdp_per_capita       56054.9
hosp_beds                NaN

STEP 9: เปลี่ยนค่า NaN (Missing Values) ที่พบ ให้มีจำนวนเป็น 0 โดยต้องเติมค่าที่ถูกต้องใส่เข้าไปแทน

Use the fillna method to fix the missing cases data for the one country affected (Hong Kong)

ใช้คำสั่ง .fillna() แทนที่ค่าที่หายไปด้วยค่าที่ผู้ใช้ระบุ

ตำแหน่ง missing data ที่ต้องการแทน.fillna(ค่าที่ต้องการแทน จะใส่ตัวเลข สูตรคำนวณ หรือ “ตัวอักษร” ก็ได้)

#use the fillna method to fix the mixing case data
#before use fillna()
print(covidtotals[totvars].isnull().sum(axis=0))
#.fillna ถ้ามีการแก้ไขต้องเริ่มรันใหม่ตั้งแต่ STEP 1 อีกครั้ง เช่น ลองใส่ .fillna(3) หรือ .fillna("Hello")
covidtotals.total_cases_pm.fillna(covidtotals.total_cases/(covidtotals.population/1000000), inplace=True)
covidtotals.total_deaths_pm.fillna(covidtotals.total_deaths/(covidtotals.population/1000000), inplace=True)
print()
#after use fillna()
print(covidtotals[totvars].isnull().sum(axis=0)) #แสดงค่าที่ใส่เข้าไปใหม่ 
covidtotals.to_csv("fill_covidtotals")
location           0
total_cases        0
total_deaths       0
total_cases_pm     1
total_deaths_pm    1
dtype: int64

location           0
total_cases        0
total_deaths       0
total_cases_pm     0
total_deaths_pm    0
dtype: int64
#แสดงผลค่า values ของข้อมูล 'HKG' หลังจากใส่ค่าใหม่ที่แก้ไข missing data แล้ว
print(covidtotals.loc[['HKG']].T)
iso_code                 HKG
lastdate          2020-05-26
location           Hong Kong
total_cases                0
total_deaths               0
total_cases_pm             0
total_deaths_pm            0
population       7.49699e+06
pop_density          7039.71
median_age              44.8
gdp_per_capita       56054.9
hosp_beds                NaN

STEP 10: ลบแถวที่มีค่า NaN (Missing Values) ออก

Use the dropna method to remove the missing cases data

ใช้คำสั่ง .dropna() ลบแถวของค่าที่หายไป

#Before use dropna
print(covidtotals)
print(covidtotals.shape)
#After use dropna
drop_covidtotals = covidtotals.dropna()
print(drop_covidtotals)
print(drop_covidtotals.shape)
drop_covidtotals.to_csv("drop_covidtotals")
 lastdate        location  ...  gdp_per_capita  hosp_beds
iso_code                              ...                           
AFG       2020-06-01     Afghanistan  ...        1803.987       0.50
ALB       2020-06-01         Albania  ...       11803.431       2.89
DZA       2020-06-01         Algeria  ...       13913.839       1.90
AND       2020-06-01         Andorra  ...             NaN        NaN
AGO       2020-06-01          Angola  ...        5819.495        NaN
...              ...             ...  ...             ...        ...
VNM       2020-06-01         Vietnam  ...        6171.884       2.60
ESH       2020-06-01  Western Sahara  ...             NaN        NaN
YEM       2020-06-01           Yemen  ...        1479.147       0.70
ZMB       2020-06-01          Zambia  ...        3689.251       2.00
ZWE       2020-06-01        Zimbabwe  ...        1899.775       1.70

[210 rows x 11 columns]
(210, 11)
            lastdate             location  ...  gdp_per_capita  hosp_beds
iso_code                                   ...                           
AFG       2020-06-01          Afghanistan  ...        1803.987       0.50
ALB       2020-06-01              Albania  ...       11803.431       2.89
DZA       2020-06-01              Algeria  ...       13913.839       1.90
ATG       2020-06-01  Antigua and Barbuda  ...       21490.943       3.80
ARG       2020-06-01            Argentina  ...       18933.907       5.00
...              ...                  ...  ...             ...        ...
VEN       2020-06-01            Venezuela  ...       16745.022       0.80
VNM       2020-06-01              Vietnam  ...        6171.884       2.60
YEM       2020-06-01                Yemen  ...        1479.147       0.70
ZMB       2020-06-01               Zambia  ...        3689.251       2.00
ZWE       2020-06-01             Zimbabwe  ...        1899.775       1.70

[156 rows x 11 columns]
(156, 11)

Workshop 7: การลบข้อมูลแถวที่ซ้ำกัน

–> Removing Duplicated Rows

Input Datasets

Question 7: เราจะทำการลบข้อมูลแถวที่ซ้ำกันได้อย่างไร

STEP 1: นำเข้า Datasets โดยทำการ Upload ไฟล์ covidcases720.csv ขึ้น Google Colab (ไฟล์นี้จะถูกลบเมื่อเราหลุดจาก Session หรือปิด Browser) หรือ Python IDE เช่น PyCharm, VSCode, Juputer Notebook, etc.

STEP 2: นำเข้า pandas library มาใช้งาน

STEP 3: ทำการอ่านไฟล์ .csv ด้วย pandas เก็บเป็น Dataframe

ใช้คำสั่ง .read_csv()

#import pandas and the COVID daily cases data:
import pandas as pd
covidcases = pd.read_csv("/content/covidcases720.csv")
print(covidcases)
iso_code continent  ... life_expectancy           region
0          AFG      Asia  ...           64.83       South Asia
1          AFG      Asia  ...           64.83       South Asia
2          AFG      Asia  ...           64.83       South Asia
3          AFG      Asia  ...           64.83       South Asia
4          AFG      Asia  ...           64.83       South Asia
...        ...       ...  ...             ...              ...
29524      ZWE    Africa  ...           61.49  Southern Africa
29525      ZWE    Africa  ...           61.49  Southern Africa
29526      ZWE    Africa  ...           61.49  Southern Africa
29527      ZWE    Africa  ...           61.49  Southern Africa
29528      ZWE    Africa  ...           61.49  Southern Africa

[29529 rows x 35 columns]

STEP 4: สร้างรายการ lists ของข้อมูล covid daily cases สำหรับคอลัมน์ cumulative และ demographic

ใช้คำสั่ง [ ‘column_names’ ] ในการสร้าง lists รายการของชุดข้อมูล

#create lists for daily cases, for cumulative columns and for demographic columns
dailyvars = ['casedate','new_cases','new_deaths']
totvars = ['location','total_cases','total_deaths']
demovars = ['population','population_density','median_age',
  'gdp_per_capita','hospital_beds_per_thousand','region']
print(covidcases[dailyvars + totvars + demovars].head(3).T)
     0            1            2
casedate                     2019-12-31   2020-01-01   2020-01-02
new_cases                             0            0            0
new_deaths                            0            0            0
location                    Afghanistan  Afghanistan  Afghanistan
total_cases                           0            0            0
total_deaths                          0            0            0
population                  3.89283e+07  3.89283e+07  3.89283e+07
population_density               54.422       54.422       54.422
median_age                         18.6         18.6         18.6
gdp_per_capita                  1803.99      1803.99      1803.99
hospital_beds_per_thousand          0.5          0.5          0.5
region                       South Asia   South Asia   South Asia

STEP 5: สร้าง DataFrame ของข้อมูล covid daily data

#create a daily data frames
coviddaily = covidcases[['location'] + dailyvars]
print(coviddaily.shape)
print(coviddaily.head())
(29529, 4)
      location    casedate  new_cases  new_deaths
0  Afghanistan  2019-12-31        0.0         0.0
1  Afghanistan  2020-01-01        0.0         0.0
2  Afghanistan  2020-01-02        0.0         0.0
3  Afghanistan  2020-01-03        0.0         0.0
4  Afghanistan  2020-01-04        0.0         0.0

STEP 6: เลือก 1 แถวต่อประเทศ ที่ไม่ซ้ำกัน

select one row per country

ใช้คำสั่ง sort_values เรียงลำดับข้อมูล

ใช้คำสั่ง drop_duplicates ลบแถวที่มีค่าข้อมูลซ้ำกัน

–> drop_duplicates ใช้ได้กับ column ธรรมดา ไม่ใช้กับ column index

ใช้คำสั่ง rename(columns={ ‘old_column_name’ : ‘new_column_name’ }) เปลี่ยนชื่อคอลัมน์ใหม่

#select one row per country
#นับจำนวน location ที่ไม่ซ้ำกัน
print(covidcases.location.nunique())  
#รวม columns
#เรียงลำดับค่า location (ตามตัวอักษร) และ casedate (ตามวันเดือนปี))
#เปลี่ยนชื่อคอลัมน์ casedate เป็นชื่อ lastdate
coviddemo = covidcases[['casedate'] + totvars + demovars]. \
        sort_values(['location','casedate']). \
        rename(columns={'casedate':'lastdate'})
print(coviddemo.shape)  #แสดง rows และ columns
print(coviddemo.head(3))  #แสดงรายการบนสุด 3 รายการ
print(coviddemo.head(3).T) #Transpose
209
(29529, 10)
     lastdate     location  ...  hospital_beds_per_thousand      region
0  2019-12-31  Afghanistan  ...                         0.5  South Asia
1  2020-01-01  Afghanistan  ...                         0.5  South Asia
2  2020-01-02  Afghanistan  ...                         0.5  South Asia

[3 rows x 10 columns]
                                      0            1            2
lastdate                     2019-12-31   2020-01-01   2020-01-02
location                    Afghanistan  Afghanistan  Afghanistan
total_cases                           0            0            0
total_deaths                          0            0            0
population                  3.89283e+07  3.89283e+07  3.89283e+07
population_density               54.422       54.422       54.422
median_age                         18.6         18.6         18.6
gdp_per_capita                  1803.99      1803.99      1803.99
hospital_beds_per_thousand          0.5          0.5          0.5
region                       South Asia   South Asia   South Asia
#ลบแถวที่ชื่อประเทศซ้ำกัน location โดยเก็บเฉพาะแถวข้อมูลล่าสุด ด้วยคำสั่ง drop_duplicates , keep='last'
coviddemo = covidcases[['casedate'] + totvars + demovars]. \
        sort_values(['location','casedate']). \
        drop_duplicates(['location'], keep='last'). \
        rename(columns={'casedate':'lastdate'})
print(coviddemo.shape)
print(coviddemo.head(3))
print(coviddemo.head(3).T)
coviddemo.to_csv("/content/coviddemo")
(209, 10)
       lastdate     location  ...  hospital_beds_per_thousand          region
184  2020-07-12  Afghanistan  ...                        0.50      South Asia
310  2020-07-12      Albania  ...                        2.89  Eastern Europe
500  2020-07-12      Algeria  ...                        1.90    North Africa

[3 rows x 10 columns]
                                    184             310           500
lastdate                     2020-07-12      2020-07-12    2020-07-12
location                    Afghanistan         Albania       Algeria
total_cases                       34451            3371         18712
total_deaths                       1010              89          1004
population                  3.89283e+07      2.8778e+06    4.3851e+07
population_density               54.422         104.871        17.348
median_age                         18.6              38          29.1
gdp_per_capita                  1803.99         11803.4       13913.8
hospital_beds_per_thousand          0.5            2.89           1.9
region                       South Asia  Eastern Europe  North Africa

STEP 7: แสดงค่าผลรวมของแต่ละประเทศ

sum values for each group

ใช้คำสั่ง .groupby() จัดกลุ่มตาม location as_index = False ไม่ใช่ index ถ้า True ใช่ index

agg({‘column_name’ : ‘calculate’) –> calculate = sum, mean, count, size, std, var, sem, describe, first, last, nth, min, max

covidtotals = covidcases.groupby(['location'], as_index=False).\
  agg({'new_cases':'sum','new_deaths':'sum','median_age':'last',
    'gdp_per_capita':'last','region':'last','casedate':'last',
    'population':'last'}).\
  rename(columns={'new_cases':'total_cases',
    'new_deaths':'total_deaths','casedate':'lastdate'})
print(covidtotals.shape)
print(covidtotals.head(3))
print(covidtotals.head(3).T)
(209, 8)
      location  total_cases  ...    lastdate  population
0  Afghanistan      34451.0  ...  2020-07-12  38928341.0
1      Albania       3371.0  ...  2020-07-12   2877800.0
2      Algeria      18712.0  ...  2020-07-12  43851043.0

[3 rows x 8 columns]
                          0               1             2
location        Afghanistan         Albania       Algeria
total_cases           34451            3371         18712
total_deaths           1010              89          1004
median_age             18.6              38          29.1
gdp_per_capita      1803.99         11803.4       13913.8
region           South Asia  Eastern Europe  North Africa
lastdate         2020-07-12      2020-07-12    2020-07-12
population      3.89283e+07      2.8778e+06    4.3851e+07

Workshop 8: ใช้ groupby จัดระเบียบข้อมูลตามกลุ่ม

–> Using groupby to organize data by groups

Input Datasets

Question 8: เราจะเลือกจัดระเบียบข้อมูลเฉพาะกลุ่มที่เราสนใจได้อย่างไร?

STEP 1: นำเข้า Datasets โดยทำการ Upload ไฟล์ coviddaily720.csv ขึ้น Google Colab (ไฟล์นี้จะถูกลบเมื่อเราหลุดจาก Session หรือปิด Browser) หรือ Python IDE เช่น PyCharm, VSCode, Juputer Notebook, etc.

STEP 2: นำเข้า pandas และ numpy libraries มาใช้งาน

STEP 3: ทำการอ่านไฟล์ .csv ด้วย pandas เก็บเป็น Dataframe

ใช้คำสั่ง .read_csv() pasrse_dates=[ “colunm_name” ] เป็น data type ชนิด datetime

#import pandas and numpy, and load the covid data
import pandas as pd
import numpy as np
coviddaily = pd.read_csv("/content/coviddaily720.csv", parse_dates=["casedate"])
print(coviddaily)
print()
print(coviddaily.info())
     iso_code   casedate  ... hosp_beds           region
0          AFG 2019-12-31  ...       0.5       South Asia
1          AFG 2020-01-01  ...       0.5       South Asia
2          AFG 2020-01-02  ...       0.5       South Asia
3          AFG 2020-01-03  ...       0.5       South Asia
4          AFG 2020-01-04  ...       0.5       South Asia
...        ...        ...  ...       ...              ...
29208      ZWE 2020-07-08  ...       1.7  Southern Africa
29209      ZWE 2020-07-09  ...       1.7  Southern Africa
29210      ZWE 2020-07-10  ...       1.7  Southern Africa
29211      ZWE 2020-07-11  ...       1.7  Southern Africa
29212      ZWE 2020-07-12  ...       1.7  Southern Africa

[29213 rows x 12 columns]

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 29213 entries, 0 to 29212
Data columns (total 12 columns):
 #   Column          Non-Null Count  Dtype         
---  ------          --------------  -----         
 0   iso_code        29213 non-null  object        
 1   casedate        29213 non-null  datetime64[ns]
 2   location        29213 non-null  object        
 3   continent       29213 non-null  object        
 4   new_cases       29213 non-null  float64       
 5   new_deaths      29213 non-null  float64       
 6   population      29213 non-null  float64       
 7   pop_density     27959 non-null  float64       
 8   median_age      26343 non-null  float64       
 9   gdp_per_capita  26029 non-null  float64       
 10  hosp_beds       24015 non-null  float64       
 11  region          29213 non-null  object        
dtypes: datetime64[ns](1), float64(7), object(4)
memory usage: 2.7+ MB
None

STEP 4: สร้าง DataFrame แบบจัดตามกลุ่ม

ใช้คำสั่ง .groupby([ ‘column_name’ ]) จัดข้อมูลตามกลุ่ม

#create a pandas groupby data frame
countrytots = coviddaily.groupby(['location']) #จัดระเบียบตามกลุ่มข้อมูล ซ้ำกันจะรวมกัน
print(type(countrytots)) #ชนิด DataFrame แบบ GroupBy
<class 'pandas.core.groupby.generic.DataFrameGroupBy'>

STEP 5: สร้าง DataFrame ของข้อมูล first rows และ last rows ของแต่ละประเทศ

ใช้คำสั่ง .first().iloc[row_index, column_index] แถวบนลงล่าง [ตำแหน่งเลข index เริ่มต้น : สิ้นสุด+1]

ใช้คำสั่ง .last().iloc[row_index, column_index] แถวล่างขึ้นบน [ตำแหน่งเลข index เริ่มต้น : สิ้นสุด+1]

#create data frames for the first and last rows for each country
print(countrytots.first().iloc[0:5, 0:5])  #แถวบนลงล่าง 
print(countrytots.last().iloc[0:5, 0:5])   #แถวล่างขึ้นบน
print(type(countrytots.first()))
print(type(countrytots.last()))
iso_code   casedate continent  new_cases  new_deaths
location                                                        
Afghanistan      AFG 2019-12-31      Asia        0.0         0.0
Albania          ALB 2020-03-09    Europe        2.0         0.0
Algeria          DZA 2019-12-31    Africa        0.0         0.0
Andorra          AND 2020-03-03    Europe        1.0         0.0
Angola           AGO 2020-03-22    Africa        2.0         0.0
            iso_code   casedate continent  new_cases  new_deaths
location                                                        
Afghanistan      AFG 2020-07-12      Asia       85.0        16.0
Albania          ALB 2020-07-12    Europe       93.0         4.0
Algeria          DZA 2020-07-12    Africa      904.0        16.0
Andorra          AND 2020-07-12    Europe        0.0         0.0
Angola           AGO 2020-07-12    Africa       25.0         2.0
<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>

STEP 6: เลือกแถวข้อมูลทั้งหมดของประเทศที่ต้องการ

get all of the rows for a country

ใช้คำสั่ง get_group( ‘value’ ).iloc[ row_index, column_index]

#get all of the rows for a country
print(countrytots.get_group('Zimbabwe').iloc[0:5, 0:5])  #เลือกค่าที่อยู่ในกลุ่มที่ทำการ groupby
print(countrytots.get_group('China').iloc[0:6,0:5])  
print(countrytots.get_group('Thailand').iloc[73:79,0:5])
iso_code   casedate continent  new_cases  new_deaths
29099      ZWE 2020-03-21    Africa        1.0         0.0
29100      ZWE 2020-03-22    Africa        1.0         0.0
29101      ZWE 2020-03-23    Africa        0.0         0.0
29102      ZWE 2020-03-24    Africa        0.0         1.0
29103      ZWE 2020-03-25    Africa        0.0         0.0
     iso_code   casedate continent  new_cases  new_deaths
5678      CHN 2019-12-31      Asia       27.0         0.0
5679      CHN 2020-01-01      Asia        0.0         0.0
5680      CHN 2020-01-02      Asia        0.0         0.0
5681      CHN 2020-01-03      Asia       17.0         0.0
5682      CHN 2020-01-04      Asia        0.0         0.0
5683      CHN 2020-01-05      Asia       15.0         0.0
      iso_code   casedate continent  new_cases  new_deaths
26395      THA 2020-03-20      Asia       35.0         0.0
26396      THA 2020-03-21      Asia      154.0         0.0
26397      THA 2020-03-22      Asia      233.0         0.0
26398      THA 2020-03-23      Asia      122.0         0.0
26399      THA 2020-03-24      Asia      106.0         3.0
26400      THA 2020-03-25      Asia      107.0         0.0


STEP 7:
 สร้างคำสั่งวนซ้ำพร้อมกันหลายประเทศ

get all of the rows for a country

ใช้คำสั่ง for เขียนโปรแกรมวนซ้ำ

#loop through the groups 
for name, group in countrytots:
  if (name in ['China','Thailand','United States']): #เวลาแสดงผลจะเรียงตามตัวอักษร
    print(group.iloc[0:30, 0:5])
iso_code   casedate location continent  new_cases
5678      CHN 2019-12-31    China      Asia       27.0
5679      CHN 2020-01-01    China      Asia        0.0
5680      CHN 2020-01-02    China      Asia        0.0
5681      CHN 2020-01-03    China      Asia       17.0
5682      CHN 2020-01-04    China      Asia        0.0
5683      CHN 2020-01-05    China      Asia       15.0
5684      CHN 2020-01-06    China      Asia        0.0
5685      CHN 2020-01-07    China      Asia        0.0
5686      CHN 2020-01-08    China      Asia        0.0
5687      CHN 2020-01-09    China      Asia        0.0
5688      CHN 2020-01-10    China      Asia        0.0
5689      CHN 2020-01-11    China      Asia        0.0
5690      CHN 2020-01-12    China      Asia        0.0
5691      CHN 2020-01-13    China      Asia        0.0
5692      CHN 2020-01-14    China      Asia        0.0
5693      CHN 2020-01-15    China      Asia        0.0
5694      CHN 2020-01-16    China      Asia        0.0
5695      CHN 2020-01-17    China      Asia        4.0
5696      CHN 2020-01-18    China      Asia       17.0
5697      CHN 2020-01-19    China      Asia      136.0
5698      CHN 2020-01-20    China      Asia       19.0
5699      CHN 2020-01-21    China      Asia      151.0
5700      CHN 2020-01-22    China      Asia      140.0
5701      CHN 2020-01-23    China      Asia       97.0
5702      CHN 2020-01-24    China      Asia      259.0
5703      CHN 2020-01-25    China      Asia      441.0
5704      CHN 2020-01-26    China      Asia      665.0
5705      CHN 2020-01-27    China      Asia      787.0
5706      CHN 2020-01-28    China      Asia     1753.0
5707      CHN 2020-01-29    China      Asia     1466.0
      iso_code   casedate  location continent  new_cases
26322      THA 2019-12-31  Thailand      Asia        0.0
26323      THA 2020-01-01  Thailand      Asia        0.0
26324      THA 2020-01-02  Thailand      Asia        0.0
26325      THA 2020-01-03  Thailand      Asia        0.0
26326      THA 2020-01-04  Thailand      Asia        0.0
26327      THA 2020-01-05  Thailand      Asia        0.0
26328      THA 2020-01-06  Thailand      Asia        0.0
26329      THA 2020-01-07  Thailand      Asia        0.0
26330      THA 2020-01-08  Thailand      Asia        0.0
26331      THA 2020-01-09  Thailand      Asia        0.0
26332      THA 2020-01-10  Thailand      Asia        0.0
26333      THA 2020-01-11  Thailand      Asia        0.0
26334      THA 2020-01-12  Thailand      Asia        0.0
26335      THA 2020-01-13  Thailand      Asia        1.0
26336      THA 2020-01-14  Thailand      Asia        0.0
26337      THA 2020-01-15  Thailand      Asia        0.0
26338      THA 2020-01-16  Thailand      Asia        0.0
26339      THA 2020-01-17  Thailand      Asia        1.0
26340      THA 2020-01-18  Thailand      Asia        0.0
26341      THA 2020-01-19  Thailand      Asia        0.0
26342      THA 2020-01-20  Thailand      Asia        0.0
26343      THA 2020-01-21  Thailand      Asia        0.0
26344      THA 2020-01-22  Thailand      Asia        2.0
26345      THA 2020-01-23  Thailand      Asia        0.0
26346      THA 2020-01-24  Thailand      Asia        0.0
26347      THA 2020-01-25  Thailand      Asia        1.0
26348      THA 2020-01-26  Thailand      Asia        0.0
26349      THA 2020-01-27  Thailand      Asia        3.0
26350      THA 2020-01-28  Thailand      Asia        6.0
26351      THA 2020-01-29  Thailand      Asia        0.0
      iso_code   casedate       location      continent  new_cases
27837      USA 2019-12-31  United States  North America        0.0
27838      USA 2020-01-01  United States  North America        0.0
27839      USA 2020-01-02  United States  North America        0.0
27840      USA 2020-01-03  United States  North America        0.0
27841      USA 2020-01-04  United States  North America        0.0
27842      USA 2020-01-05  United States  North America        0.0
27843      USA 2020-01-06  United States  North America        0.0
27844      USA 2020-01-07  United States  North America        0.0
27845      USA 2020-01-08  United States  North America        0.0
27846      USA 2020-01-09  United States  North America        0.0
27847      USA 2020-01-10  United States  North America        0.0
27848      USA 2020-01-11  United States  North America        0.0
27849      USA 2020-01-12  United States  North America        0.0
27850      USA 2020-01-13  United States  North America        0.0
27851      USA 2020-01-14  United States  North America        0.0
27852      USA 2020-01-15  United States  North America        0.0
27853      USA 2020-01-16  United States  North America        0.0
27854      USA 2020-01-17  United States  North America        0.0
27855      USA 2020-01-18  United States  North America        0.0
27856      USA 2020-01-19  United States  North America        0.0
27857      USA 2020-01-20  United States  North America        0.0
27858      USA 2020-01-21  United States  North America        1.0
27859      USA 2020-01-22  United States  North America        0.0
27860      USA 2020-01-23  United States  North America        0.0
27861      USA 2020-01-24  United States  North America        0.0
27862      USA 2020-01-25  United States  North America        1.0
27863      USA 2020-01-26  United States  North America        0.0
27864      USA 2020-01-27  United States  North America        3.0
27865      USA 2020-01-28  United States  North America        0.0
27866      USA 2020-01-29  United States  North America        0.0

STEP 8: แสดงค่าผลรวมจำนวนแถวที่เก็บข้อมูลของแต่ละประเทศ

sum values for each group

ใช้คำสั่ง .size() แสดงจำนวนแถวทั้งหมด

#show the number of rows for each country
print(countrytots.size())
location
Afghanistan       185
Albania           126
Algeria           190
Andorra           121
Angola            113
                 ... 
Vietnam           191
Western Sahara     78
Yemen              94
Zambia            116
Zimbabwe          114
Length: 209, dtype: int64

STEP 9: แสดงค่าสถิติของแต่ละประเทศ

ใช้คำสั่ง .describe() หาค่า summary statistics

ใช้คำสั่ง .sum() หาผลรวม

#show summary statistics by country
print(countrytots.new_cases.describe().head())
print()
print(countrytots.new_cases.sum().head())
count        mean         std  min  25%   50%     75%     max
location                                                                  
Afghanistan  185.0  186.221622  257.305202  0.0  0.0  37.0  302.00  1063.0
Albania      126.0   26.753968   24.651389  0.0  9.0  17.0   35.50    93.0
Algeria      190.0   98.484211  123.980103  0.0  0.0  88.0  149.75   904.0
Andorra      121.0    7.066116   12.716614  0.0  0.0   1.0    9.00    79.0
Angola       113.0    4.274336    8.509709  0.0  0.0   1.0    5.00    62.0

location
Afghanistan    34451.0
Albania         3371.0
Algeria        18712.0
Andorra          855.0
Angola           483.0
Name: new_cases, dtype: float64

Workshop 9: ใช้ Aggregation Functions ร่วมกับ groupby จัดระเบียบข้อมูลตามกลุ่ม

–> Using more complicated aggregation functions with groupby

Input Datasets

  • nls97b.csv – the National Longitudinal Survey (NLS) 1997-2018.

Question 9: เราสามารถรวมกลุ่มของข้อมูลเพิ่มเติมเพิ่มคำนวณค่าที่ต้องการได้ด้วยวิธีการใด?

STEP 1: นำเข้า Datasets โดยทำการ Upload ไฟล์ nls97b.csv ขึ้น Google Colab (ไฟล์นี้จะถูกลบเมื่อเราหลุดจาก Session หรือปิด Browser) หรือ Python IDE เช่น PyCharm, VSCode, Juputer Notebook, etc.

STEP 2: นำเข้า pandas library มาใช้งาน

STEP 3: ทำการอ่านไฟล์ .csv ด้วย pandas เก็บเป็น Dataframe

ใช้คำสั่ง .read_csv()

STEP 4: ตั้งค่าและแสดง index และ size ของ nls97b data

ใช้คำสั่ง set_index()

#import pandas, load the nls97 feather file
import pandas as pd
nls97b = pd.read_csv("/content/nls97b.csv")
print(nls97b)
nls97b.set_index("personid", inplace=True)
print(nls97b)
personid  gender  ...      colenrfeb17      colenroct17
0       100061  Female  ...  1. Not enrolled  1. Not enrolled
1       100139    Male  ...  1. Not enrolled  1. Not enrolled
2       100284    Male  ...  1. Not enrolled  1. Not enrolled
3       100292    Male  ...              NaN              NaN
4       100583    Male  ...  1. Not enrolled  1. Not enrolled
...        ...     ...  ...              ...              ...
8979    999291  Female  ...  1. Not enrolled  1. Not enrolled
8980    999406    Male  ...  1. Not enrolled  1. Not enrolled
8981    999543  Female  ...  1. Not enrolled  1. Not enrolled
8982    999698  Female  ...  1. Not enrolled  1. Not enrolled
8983    999963  Female  ...  1. Not enrolled  1. Not enrolled

[8984 rows x 89 columns]
          gender  birthmonth  ...      colenrfeb17      colenroct17
personid                      ...                                  
100061    Female           5  ...  1. Not enrolled  1. Not enrolled
100139      Male           9  ...  1. Not enrolled  1. Not enrolled
100284      Male          11  ...  1. Not enrolled  1. Not enrolled
100292      Male           4  ...              NaN              NaN
100583      Male           1  ...  1. Not enrolled  1. Not enrolled
...          ...         ...  ...              ...              ...
999291    Female           4  ...  1. Not enrolled  1. Not enrolled
999406      Male           7  ...  1. Not enrolled  1. Not enrolled
999543    Female           8  ...  1. Not enrolled  1. Not enrolled
999698    Female           5  ...  1. Not enrolled  1. Not enrolled
999963    Female           9  ...  1. Not enrolled  1. Not enrolled

[8984 rows x 88 columns]

STEP 5: แสดงจำนวน data types และ non-null value

ใช้คำสั่ง info()

ใช้คำสั่ง .iloc[ index_row, index_column ]

#review the structure of the nls97 data
print(nls97b.info())   #all columns
print()
print(nls97b.iloc[:,0:7].info())   #.iloc[index_row, index_column]
<class 'pandas.core.frame.DataFrame'>
Int64Index: 8984 entries, 100061 to 999963
Data columns (total 88 columns):
 #   Column                 Non-Null Count  Dtype  
---  ------                 --------------  -----  
 0   gender                 8984 non-null   object 
 1   birthmonth             8984 non-null   int64  
 2   birthyear              8984 non-null   int64  
 3   highestgradecompleted  6663 non-null   float64
 4   maritalstatus          6672 non-null   object 
 5   childathome            4791 non-null   float64
 6   childnotathome         4791 non-null   float64
 7   wageincome             5091 non-null   float64
 8   weeklyhrscomputer      6710 non-null   object 
 9   weeklyhrstv            6711 non-null   object 
 10  nightlyhrssleep        6706 non-null   float64
 11  satverbal              1406 non-null   float64
 12  satmath                1407 non-null   float64
 13  gpaoverall             6004 non-null   float64
 14  gpaenglish             5798 non-null   float64
 15  gpamath                5766 non-null   float64
 16  gpascience             5684 non-null   float64
 17  highestdegree          8953 non-null   object 
 18  govprovidejobs         1833 non-null   object 
 19  govpricecontrols       1859 non-null   object 
 20  govhealthcare          1874 non-null   object 
 21  govelderliving         1872 non-null   object 
 22  govindhelp             1815 non-null   object 
 23  govunemp               1811 non-null   object 
 24  govincomediff          1775 non-null   object 
 25  govcollegefinance      1875 non-null   object 
 26  govdecenthousing       1847 non-null   object 
 27  govprotectenvironment  1860 non-null   object 
 28  weeksworked00          8603 non-null   float64
 29  weeksworked01          8564 non-null   float64
 30  weeksworked02          8556 non-null   float64
 31  weeksworked03          8490 non-null   float64
 32  weeksworked04          8458 non-null   float64
 33  weeksworked05          8403 non-null   float64
 34  weeksworked06          8340 non-null   float64
 35  weeksworked07          8272 non-null   float64
 36  weeksworked08          8186 non-null   float64
 37  weeksworked09          8146 non-null   float64
 38  weeksworked10          8054 non-null   float64
 39  weeksworked11          7968 non-null   float64
 40  weeksworked12          7747 non-null   float64
 41  weeksworked13          7680 non-null   float64
 42  weeksworked14          7612 non-null   float64
 43  weeksworked15          7389 non-null   float64
 44  weeksworked16          7068 non-null   float64
 45  weeksworked17          6670 non-null   float64
 46  colenrfeb97            1250 non-null   object 
 47  colenroct97            8501 non-null   object 
 48  colenrfeb98            8501 non-null   object 
 49  colenroct98            8888 non-null   object 
 50  colenrfeb99            8865 non-null   object 
 51  colenroct99            8851 non-null   object 
 52  colenrfeb00            8820 non-null   object 
 53  colenroct00            8805 non-null   object 
 54  colenrfeb01            8786 non-null   object 
 55  colenroct01            8758 non-null   object 
 56  colenrfeb02            8732 non-null   object 
 57  colenroct02            8698 non-null   object 
 58  colenrfeb03            8658 non-null   object 
 59  colenroct03            8622 non-null   object 
 60  colenrfeb04            8578 non-null   object 
 61  colenroct04            8546 non-null   object 
 62  colenrfeb05            8508 non-null   object 
 63  colenroct05            8471 non-null   object 
 64  colenrfeb06            8426 non-null   object 
 65  colenroct06            8407 non-null   object 
 66  colenrfeb07            8352 non-null   object 
 67  colenroct07            8331 non-null   object 
 68  colenrfeb08            8289 non-null   object 
 69  colenroct08            8280 non-null   object 
 70  colenrfeb09            8236 non-null   object 
 71  colenroct09            8193 non-null   object 
 72  colenrfeb10            8116 non-null   object 
 73  colenroct10            8091 non-null   object 
 74  colenrfeb11            8037 non-null   object 
 75  colenroct11            7972 non-null   object 
 76  colenrfeb12            7794 non-null   object 
 77  colenroct12            7754 non-null   object 
 78  colenrfeb13            7754 non-null   object 
 79  colenroct13            7754 non-null   object 
 80  colenrfeb14            7624 non-null   object 
 81  colenroct14            7469 non-null   object 
 82  colenrfeb15            7469 non-null   object 
 83  colenroct15            7469 non-null   object 
 84  colenrfeb16            7036 non-null   object 
 85  colenroct16            6733 non-null   object 
 86  colenrfeb17            6733 non-null   object 
 87  colenroct17            6734 non-null   object 
dtypes: float64(29), int64(2), object(57)
memory usage: 6.1+ MB
None

<class 'pandas.core.frame.DataFrame'>
Int64Index: 8984 entries, 100061 to 999963
Data columns (total 7 columns):
 #   Column                 Non-Null Count  Dtype  
---  ------                 --------------  -----  
 0   gender                 8984 non-null   object 
 1   birthmonth             8984 non-null   int64  
 2   birthyear              8984 non-null   int64  
 3   highestgradecompleted  6663 non-null   float64
 4   maritalstatus          6672 non-null   object 
 5   childathome            4791 non-null   float64
 6   childnotathome         4791 non-null   float64
dtypes: float64(3), int64(2), object(2)
memory usage: 561.5+ KB
None

STEP 6: แสดงค่าข้อมูลของ columns เพิ่มเติม

ใช้คำสั่ง for เขียนโปรแกรมวนซ้ำ

#look again at some of the data
catvars = ['gender','maritalstatus','highestdegree']
for col in catvars:
  print(col, nls97b[col].value_counts().sort_index(), sep="\n\n", end="\n\n\n") #sep ทำหลัง , end ทำจบ
gender

Female    4385
Male      4599
Name: gender, dtype: int64


maritalstatus

Divorced          663
Married          3066
Never-married    2766
Separated         154
Widowed            23
Name: maritalstatus, dtype: int64


highestdegree

0. None             953
1. GED             1146
2. High School     3667
3. Associates       737
4. Bachelors       1673
5. Masters          603
6. PhD               54
7. Professional     120
Name: highestdegree, dtype: int64

STEP 7: แสดงค่าทางสถิติเชิงพรรณนา Descriptive Statistics

ใช้คำสั่ง .describe() แสดงค่าสถิติต่าง ๆ ได้แก่ count mean std min 25% 50% 75% และ max

#review some descriptive statistics
contvars = ['satmath','satverbal','weeksworked06','gpaoverall',
  'childathome']

print(nls97b[contvars].describe())
satmath    satverbal  weeksworked06   gpaoverall  childathome
count  1407.000000  1406.000000    8340.000000  6004.000000  4791.000000
mean    500.590618   499.724040      38.429976     2.818408     1.859320
std     114.953309   112.166256      18.921281     0.616357     1.259053
min       7.000000    14.000000       0.000000     0.100000     0.000000
25%     430.000000   430.000000      27.000000     2.430000     1.000000
50%     500.000000   500.000000      51.000000     2.860000     2.000000
75%     580.000000   570.000000      52.000000     3.260000     3.000000
max     800.000000   800.000000      52.000000     4.170000     9.000000

STEP 8: หาค่า Mean ของคะแนน Math แบ่งตามกลุ่ม gender

ใช้คำสั่ง .groupby( ‘column ที่ต้องการจัดกลุ่ม’ )[ ‘column ที่ต้องการคำนวณ’ ].

ใช้คำสั่ง .mean หาค่าเฉลี่ย

#look at sat math scores by gender
print(nls97b.groupby('gender')['satmath'].mean())  #ลองเปลี่ยนเป็น sum, std, min, max
gender
Female    486.647757
Male      516.875193
Name: satmath, dtype: float64

STEP 9: ใส่ข้อมูลกลุ่ม column เพิ่มเติม เพื่อแบ่งเป็น group ย่อย

#look at sat math scores by gender and highest degree earned
print(nls97b.groupby(['gender','highestdegree'])['satmath'].mean())
gender  highestdegree  
Female  0. None            332.600000
        1. GED             405.000000
        2. High School     430.769231
        3. Associates      458.032787
        4. Bachelors       501.945513
        5. Masters         508.271523
        6. PhD             575.454545
        7. Professional    599.411765
Male    0. None            540.000000
        1. GED             320.000000
        2. High School     467.740586
        3. Associates      481.111111
        4. Bachelors       542.163793
        5. Masters         574.444444
        6. PhD             621.428571
        7. Professional    587.727273
Name: satmath, dtype: float64

STEP 10: ใส่ข้อมูลค่า columns ที่ต้องการค่า math เพิ่มเติม

#look at sat math and verbal scores by gender and highest degree earned
print(nls97b.groupby(['gender','highestdegree'])[['satmath','satverbal']].mean())
  satmath   satverbal
gender highestdegree                          
Female 0. None          332.600000  408.800000
       1. GED           405.000000  390.000000
       2. High School   430.769231  444.314917
       3. Associates    458.032787  466.229508
       4. Bachelors     501.945513  506.294872
       5. Masters       508.271523  533.927152
       6. PhD           575.454545  558.181818
       7. Professional  599.411765  587.058824
Male   0. None          540.000000  483.333333
       1. GED           320.000000  360.000000
       2. High School   467.740586  457.196653
       3. Associates    481.111111  462.444444
       4. Bachelors     542.163793  527.844828
       5. Masters       574.444444  545.222222
       6. PhD           621.428571  622.857143
       7. Professional  587.727273  591.818182

STEP 11: เพิ่มให้มีการคำนวณค่าทางคณิตศาสตร์ต่าง ๆ

ใช้คำสั่ง .agg( [ ‘count’, ‘mean’, ‘sum’, ‘max’, ‘min’, ‘std’ ] ) แสดงผลการคำนวณต่าง ๆ

#add max and standard deviations
print(nls97b.groupby(['gender','highestdegree'])['gpaoverall'].agg(['count','mean','max','std']))
count      mean   max       std
gender highestdegree                                   
Female 0. None            148  2.456419  4.00  0.669446
       1. GED             227  2.310132  3.91  0.658090
       2. High School    1212  2.774860  4.17  0.530336
       3. Associates      290  2.943483  4.00  0.495803
       4. Bachelors       734  3.238529  4.07  0.466571
       5. Masters         312  3.296186  4.08  0.432133
       6. PhD              22  3.460000  4.00  0.451885
       7. Professional     53  3.537736  4.11  0.413548
Male   0. None            193  2.218342  4.00  0.643481
       1. GED             345  2.242145  4.00  0.631721
       2. High School    1436  2.632806  4.00  0.497803
       3. Associates      236  2.727542  3.83  0.488499
       4. Bachelors       560  3.110446  4.10  0.486659
       5. Masters         170  3.304529  4.04  0.447173
       6. PhD              20  3.389000  3.99  0.551895
       7. Professional     38  3.442105  4.00  0.339301

STEP 12: รวมค่าของ colunms ที่ต้องการคำนวณ

ใช้คำสั่ง .groupby([‘column_name’]).agg()

#use a dictionary for more complicated aggregations
aggdict = {'weeksworked06':['count', 'mean', 'max','std'], 'childathome':['count', 'mean', 'max', 'std']}
print(nls97b.groupby(['highestdegree']).agg(aggdict))
print(nls97b.groupby(['maritalstatus']).agg(aggdict))
 weeksworked06                   ... childathome               
                        count       mean   max  ...        mean  max       std
highestdegree                                   ...                           
0. None                   703  29.664296  52.0  ...    1.840547  8.0  1.643333
1. GED                   1104  33.193841  52.0  ...    1.701299  9.0  1.457078
2. High School           3368  39.362233  52.0  ...    1.863845  7.0  1.263427
3. Associates             722  40.704986  52.0  ...    1.967290  6.0  1.126165
4. Bachelors             1642  42.231425  52.0  ...    1.896010  8.0  1.029267
5. Masters                601  42.198003  52.0  ...    1.918919  5.0  0.862210
6. PhD                     53  38.169811  52.0  ...    2.062500  6.0  1.105339
7. Professional           117  27.102564  52.0  ...    1.807018  4.0  0.833208

[8 rows x 8 columns]
              weeksworked06                   ... childathome               
                      count       mean   max  ...        mean  max       std
maritalstatus                                 ...                           
Divorced                660  37.546970  52.0  ...    1.496183  5.0  1.214155
Married                3033  40.321464  52.0  ...    2.132267  8.0  1.135297
Never-married          2734  37.219093  52.0  ...    1.561252  9.0  1.340663
Separated               153  33.816993  52.0  ...    1.540146  8.0  1.409081
Widowed                  23  37.130435  52.0  ...    1.777778  5.0  1.437136

[5 rows x 8 columns]

Workshop 10: ใช้ฟังก์ชันที่ผู้ใช้กำหนดเองและนำไปใช้กับ groupby เพื่อจัดระเบียบข้อมูลตามกลุ่ม

–> Using user-defined functions and apply with groupby

Input Datasets

  • nls97b.csv – the National Longitudinal Survey (NLS) 1997-2018.

Question 10: เราสามารถสร้างฟังก์ชันขึ้นมาใช้งานเองได้อย่างไร?

STEP 1: นำเข้า Datasets โดยทำการ Upload ไฟล์ nls97b.csv ขึ้น Google Colab (ไฟล์นี้จะถูกลบเมื่อเราหลุดจาก Session หรือปิด Browser) หรือ Python IDE เช่น PyCharm, VSCode, Juputer Notebook, etc.

STEP 2: นำเข้า pandas และ numpy libraries มาใช้งาน

STEP 3: ทำการอ่านไฟล์ .csv ด้วย pandas เก็บเป็น Dataframe

ใช้คำสั่ง .read_csv()

STEP 4: ตั้งค่าและแสดง index และ size ของ nls97b data

ใช้คำสั่ง set_index()

#import pandas and numpy, and load the nls data
import pandas as pd
import numpy as np
nls97b = pd.read_csv("/content/nls97b.csv")
print(nls97b)
nls97b.set_index("personid", inplace=True)
print(nls97b)
personid  gender  ...      colenrfeb17      colenroct17
0       100061  Female  ...  1. Not enrolled  1. Not enrolled
1       100139    Male  ...  1. Not enrolled  1. Not enrolled
2       100284    Male  ...  1. Not enrolled  1. Not enrolled
3       100292    Male  ...              NaN              NaN
4       100583    Male  ...  1. Not enrolled  1. Not enrolled
...        ...     ...  ...              ...              ...
8979    999291  Female  ...  1. Not enrolled  1. Not enrolled
8980    999406    Male  ...  1. Not enrolled  1. Not enrolled
8981    999543  Female  ...  1. Not enrolled  1. Not enrolled
8982    999698  Female  ...  1. Not enrolled  1. Not enrolled
8983    999963  Female  ...  1. Not enrolled  1. Not enrolled

[8984 rows x 89 columns]
          gender  birthmonth  ...      colenrfeb17      colenroct17
personid                      ...                                  
100061    Female           5  ...  1. Not enrolled  1. Not enrolled
100139      Male           9  ...  1. Not enrolled  1. Not enrolled
100284      Male          11  ...  1. Not enrolled  1. Not enrolled
100292      Male           4  ...              NaN              NaN
100583      Male           1  ...  1. Not enrolled  1. Not enrolled
...          ...         ...  ...              ...              ...
999291    Female           4  ...  1. Not enrolled  1. Not enrolled
999406      Male           7  ...  1. Not enrolled  1. Not enrolled
999543    Female           8  ...  1. Not enrolled  1. Not enrolled
999698    Female           5  ...  1. Not enrolled  1. Not enrolled
999963    Female           9  ...  1. Not enrolled  1. Not enrolled

[8984 rows x 88 columns]

STEP 5: สร้างฟังก์ชันสำหรับคำนวณพิสัยระหว่างควอไทล์ quantile 75% – 25%

create a function for calculating interquartile range

ใช้คำสั่ง def ชื่อฟังก์ชัน(paremeter): คำสั่งที่ต้องการให้ทำ

#create a function for calculating interquartile range
def iqr(x):
  return x.quantile(0.75) - x.quantile(0.25)

STEP 6: เรียกใช้ฟังก์ชัน iqr ที่สร้างขึ้น

call iqr function

#run the interquartile range function
aggdict = {'weeksworked06':['count', 'mean', iqr], 'childathome':['count', 'mean', iqr]}
print(nls97b.groupby(['highestdegree']).agg(aggdict))  #.agg() สำหรับเล่นกับค่าคำนวณ
weeksworked06                  childathome               
                        count       mean   iqr       count      mean  iqr
highestdegree                                                            
0. None                   703  29.664296  47.0         439  1.840547  3.0
1. GED                   1104  33.193841  39.0         693  1.701299  3.0
2. High School           3368  39.362233  21.0        1961  1.863845  2.0
3. Associates             722  40.704986  18.0         428  1.967290  2.0
4. Bachelors             1642  42.231425  14.0         827  1.896010  1.0
5. Masters                601  42.198003  13.0         333  1.918919  1.0
6. PhD                     53  38.169811  23.0          32  2.062500  2.0
7. Professional           117  27.102564  45.0          57  1.807018  1.0

STEP 7: สร้างฟังก์ชันคำนวณ Summary Statistics แปลงไปเป็น Series

Define a function to return selected summary statistics as a series

ใช้คำสั่ง def ชื่อฟังก์ชัน(parameter): คำสั่งที่ต้องการทำ

#define a function to return the summary statistics as a series
def gettots(x):
  out = {}
  out['qr1'] = x.quantile(0.25)
  out['med'] = x.median()
  out['qr3'] = x.quantile(0.75)
  out['count'] = x.count()
  return pd.Series(out)

STEP 8: เรียกใช้งานฟังก์ชัน gettots()

Use apply to run the function

This will create a series with a multi-index based on highestdegree values and the desired summary statistics:

#use apply to run the function
print(nls97b.groupby(['highestdegree'])['weeksworked06'].apply(gettots))  
#groupby([group_column])['value_column']
#ได้ type เป็น Series
print(type(nls97b.groupby(['highestdegree'])['weeksworked06'].apply(gettots)))
highestdegree         
0. None          qr1         5.0
                 med        34.0
                 qr3        52.0
                 count     703.0
1. GED           qr1        13.0
                 med        42.0
                 qr3        52.0
                 count    1104.0
2. High School   qr1        31.0
                 med        52.0
                 qr3        52.0
                 count    3368.0
3. Associates    qr1        34.0
                 med        52.0
                 qr3        52.0
                 count     722.0
4. Bachelors     qr1        38.0
                 med        52.0
                 qr3        52.0
                 count    1642.0
5. Masters       qr1        39.0
                 med        52.0
                 qr3        52.0
                 count     601.0
6. PhD           qr1        29.0
                 med        50.0
                 qr3        52.0
                 count      53.0
7. Professional  qr1         4.0
                 med        29.0
                 qr3        49.0
                 count     117.0
Name: weeksworked06, dtype: float64
<class 'pandas.core.series.Series'>

STEP 9: ทำการ reset_index เพื่อใช้ index ค่าเริ่มต้นแทนที่ groupby DataFrame ที่เพิ่งสร้างขึ้นมา

ใช้คำสั่ง reset_index()

#chain reset_index to set the default index
print(nls97b.groupby(['highestdegree'])['weeksworked06'].apply(gettots).reset_index()) #ย้อน index กลับไป
print(type(nls97b.groupby(['highestdegree'])['weeksworked06'].apply(gettots)))
 highestdegree level_1  weeksworked06
0           0. None     qr1            5.0
1           0. None     med           34.0
2           0. None     qr3           52.0
3           0. None   count          703.0
4            1. GED     qr1           13.0
5            1. GED     med           42.0
6            1. GED     qr3           52.0
7            1. GED   count         1104.0
8    2. High School     qr1           31.0
9    2. High School     med           52.0
10   2. High School     qr3           52.0
11   2. High School   count         3368.0
12    3. Associates     qr1           34.0
13    3. Associates     med           52.0
14    3. Associates     qr3           52.0
15    3. Associates   count          722.0
16     4. Bachelors     qr1           38.0
17     4. Bachelors     med           52.0
18     4. Bachelors     qr3           52.0
19     4. Bachelors   count         1642.0
20       5. Masters     qr1           39.0
21       5. Masters     med           52.0
22       5. Masters     qr3           52.0
23       5. Masters   count          601.0
24           6. PhD     qr1           29.0
25           6. PhD     med           50.0
26           6. PhD     qr3           52.0
27           6. PhD   count           53.0
28  7. Professional     qr1            4.0
29  7. Professional     med           29.0
30  7. Professional     qr3           49.0
31  7. Professional   count          117.0
<class 'pandas.core.series.Series'>

STEP 10: สร้าง column ย่อยใหม่

ใช้คำสั่ง .unstack() สำหรับแตกออกมาเป็น column ย่อยใหม่ แปลงแนวตั้งเป็นแนวนอนของ qr1, med, qr3, count

ทำให้ index ถูกสร้าง

#allow the index to be created
nlssums = nls97b.groupby(['highestdegree'])['weeksworked06'].apply(gettots).unstack()
print(nlssums)
print()
print(nlssums.info())
qr1   med   qr3   count
highestdegree                            
0. None           5.0  34.0  52.0   703.0
1. GED           13.0  42.0  52.0  1104.0
2. High School   31.0  52.0  52.0  3368.0
3. Associates    34.0  52.0  52.0   722.0
4. Bachelors     38.0  52.0  52.0  1642.0
5. Masters       39.0  52.0  52.0   601.0
6. PhD           29.0  50.0  52.0    53.0
7. Professional   4.0  29.0  49.0   117.0

<class 'pandas.core.frame.DataFrame'>
Index: 8 entries, 0. None to 7. Professional
Data columns (total 4 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   qr1     8 non-null      float64
 1   med     8 non-null      float64
 2   qr3     8 non-null      float64
 3   count   8 non-null      float64
dtypes: float64(4)
memory usage: 320.0+ bytes
None

STEP 11: รัน groupby โดยไม่สร้าง index เทียบกับที่สร้าง index

#run the groupby without creating an index and create a data frame
print(nls97b.groupby(['highestdegree'], as_index=False)['weeksworked06'].apply(gettots))
print()
#run allow the index to be created
print(nls97b.groupby(['highestdegree'])['weeksworked06'].apply(gettots).unstack())
highestdegree   qr1   med   qr3   count
0          0. None   5.0  34.0  52.0   703.0
1           1. GED  13.0  42.0  52.0  1104.0
2   2. High School  31.0  52.0  52.0  3368.0
3    3. Associates  34.0  52.0  52.0   722.0
4     4. Bachelors  38.0  52.0  52.0  1642.0
5       5. Masters  39.0  52.0  52.0   601.0
6           6. PhD  29.0  50.0  52.0    53.0
7  7. Professional   4.0  29.0  49.0   117.0

                  qr1   med   qr3   count
highestdegree                            
0. None           5.0  34.0  52.0   703.0
1. GED           13.0  42.0  52.0  1104.0
2. High School   31.0  52.0  52.0  3368.0
3. Associates    34.0  52.0  52.0   722.0
4. Bachelors     38.0  52.0  52.0  1642.0
5. Masters       39.0  52.0  52.0   601.0
6. PhD           29.0  50.0  52.0    53.0
7. Professional   4.0  29.0  49.0   117.0

Practice 3: สร้างฟังก์ชันและคลาสที่กำหนดโดยผู้ใช้เพื่อทำความสะอาดข้อมูลแบบอัตโนมัติ

User-Defined Functions and Classes to Automate Data Cleaning

Workshop 11: สร้างฟังก์ชันสำหรับตรวจดูคุณภาพข้อมูล

–> Functions for getting a first look at our data

Input Datasets

  • nls97f.csv – The survey started with a cohort of individuals in 1997 who were born between 1980 and 1985, with annual follow-ups each year through 2017. the National Longitudinal Survey (NLS) 1997-2017.

Question 11: สร้างฟังก์ชัน getfirstlook และ displaydict เพื่อตรวจดูข้อมูลต้องเขียนอย่างไรบ้าง?

STEP 1: นำเข้า Datasets โดยทำการ Upload ไฟล์ nls97f.csv ขึ้น Google Colab (ไฟล์นี้จะถูกลบเมื่อเราหลุดจาก Session หรือปิด Browser) หรือ Python IDE เช่น PyCharm, VSCode, Juputer Notebook, etc.

STEP 2: ทำการนำเข้า pandas library

STEP 3: ทำการอ่านไฟล์ .csv ด้วย pandas เก็บเป็น Dataframe

ใช้คำสั่ง .read_csv()

STEP 4: ตั้งค่าและแสดง index และ size ของ nls97f data

ใช้คำสั่ง set_index()

import pandas as pd
nls97 = pd.read_csv("/content/nls97f.csv")
print(nls97)
nls97.set_index('personid', inplace=True)
print(nls97)
personid  gender  birthmonth  ...      colenrfeb17      colenroct17 originalid
0       100061  Female           5  ...  1. Not enrolled  1. Not enrolled       8245
1       100139    Male           9  ...  1. Not enrolled  1. Not enrolled       3962
2       100284    Male          11  ...  1. Not enrolled  1. Not enrolled       3571
3       100292    Male           4  ...              NaN              NaN       2979
4       100583    Male           1  ...  1. Not enrolled  1. Not enrolled       8511
...        ...     ...         ...  ...              ...              ...        ...
8979    999291  Female           4  ...  1. Not enrolled  1. Not enrolled       7217
8980    999406    Male           7  ...  1. Not enrolled  1. Not enrolled          2
8981    999543  Female           8  ...  1. Not enrolled  1. Not enrolled       5113
8982    999698  Female           5  ...  1. Not enrolled  1. Not enrolled       7815
8983    999963  Female           9  ...  1. Not enrolled  1. Not enrolled        166

[8984 rows x 90 columns]
          gender  birthmonth  ...      colenroct17  originalid
personid                      ...                             
100061    Female           5  ...  1. Not enrolled        8245
100139      Male           9  ...  1. Not enrolled        3962
100284      Male          11  ...  1. Not enrolled        3571
100292      Male           4  ...              NaN        2979
100583      Male           1  ...  1. Not enrolled        8511
...          ...         ...  ...              ...         ...
999291    Female           4  ...  1. Not enrolled        7217
999406      Male           7  ...  1. Not enrolled           2
999543    Female           8  ...  1. Not enrolled        5113
999698    Female           5  ...  1. Not enrolled        7815
999963    Female           9  ...  1. Not enrolled         166

[8984 rows x 89 columns]

STEP 5: สร้างฟังก์ชัน getfiestlook เพื่อดูค่าต่าง ๆ โดยเขียนโปรแกรมรวมเซ็นการเรียกใช้งานคำสั่ง

.head(), .dtype(), .shape, .index

ใช้คำสั่ง def ชื่อฟังก์ชัน(parameter): คำสั่งที่ต้องการให้ทำ

STEP 6: สร้างฟังก์ชัน displaydict

ใช้คำสั่ง def ชื่อฟังก์ชัน(parameter): คำสั่งที่ต้องการให้ทำ

#create getfirstlook and displaydict functions
def getfirstlook(df, nrows=5, uniqueids=None):  #df คือ ข้อมูล nls97 ที่ส่งเข้ามา, uniqueids=None จะไม่เข้าเงื่อนไข if
    out = {}
    out['head'] = df.head(nrows)
    out['dtypes'] = df.dtypes
    out['nrows'] = df.shape[0] #0 คือ row
    out['ncols'] = df.shape[1] #1 คือ column
    out['index'] = df.index
    if (uniqueids is not None):
        out['uniqueids'] = df[uniqueids].nunique()
    return out

def displaydict(dicttodisplay):
    #แสดงผลข้อมูล string
    print(*(': '.join(map(str, x)) \
        for x in dicttodisplay.items()), sep='\n\n')

STEP 7: เรียกใช้งานฟังก์ชัน getfirstlook() และ displaydict()

#take a first look at the NLS data
dfinfo = getfirstlook(nls97)
displaydict(dfinfo)
head:           gender  birthmonth  ...      colenroct17  originalid
personid                      ...                             
100061    Female           5  ...  1. Not enrolled        8245
100139      Male           9  ...  1. Not enrolled        3962
100284      Male          11  ...  1. Not enrolled        3571
100292      Male           4  ...              NaN        2979
100583      Male           1  ...  1. Not enrolled        8511

[5 rows x 89 columns]

dtypes: gender                    object
birthmonth                 int64
birthyear                  int64
highestgradecompleted    float64
maritalstatus             object
                          ...   
colenrfeb16               object
colenroct16               object
colenrfeb17               object
colenroct17               object
originalid                 int64
Length: 89, dtype: object

nrows: 8984

ncols: 89

index: Int64Index([100061, 100139, 100284, 100292, 100583, 100833, 100931, 101089,
            101122, 101132,
            ...
            998997, 999031, 999053, 999087, 999103, 999291, 999406, 999543,
            999698, 999963],
           dtype='int64', name='personid', length=8984)

STEP 8: ส่งค่า valeus ไปยัง parameter nrows และ uniqueid

#pass values to the nrows and uniqueid parameters
dfinfo = getfirstlook(nls97,2,'originalid') #แสดงจำนวน uniqueids เข้าเงื่อนไข if นับจำนวน uniqueids
displaydict(dfinfo)
head:           gender  birthmonth  ...      colenroct17  originalid
personid                      ...                             
100061    Female           5  ...  1. Not enrolled        8245
100139      Male           9  ...  1. Not enrolled        3962

[2 rows x 89 columns]

dtypes: gender                    object
birthmonth                 int64
birthyear                  int64
highestgradecompleted    float64
maritalstatus             object
                          ...   
colenrfeb16               object
colenroct16               object
colenrfeb17               object
colenroct17               object
originalid                 int64
Length: 89, dtype: object

nrows: 8984

ncols: 89

index: Int64Index([100061, 100139, 100284, 100292, 100583, 100833, 100931, 101089,
            101122, 101132,
            ...
            998997, 999031, 999053, 999087, 999103, 999291, 999406, 999543,
            999698, 999963],
           dtype='int64', name='personid', length=8984)

uniqueids: 8984

STEP 9: แสดงข้อมูลแต่ละชุดคำสั่งที่ต้องการ

#work with some of the dictionary keys and values
print(dfinfo['nrows'])
print(dfinfo['dtypes'])
print(dfinfo['nrows'] == dfinfo['uniqueids']) #complete data คือ index เท่ากัน
8984
gender                    object
birthmonth                 int64
birthyear                  int64
highestgradecompleted    float64
maritalstatus             object
                          ...   
colenrfeb16               object
colenroct16               object
colenrfeb17               object
colenroct17               object
originalid                 int64
Length: 89, dtype: object
True

Workshop 12: สร้างฟังก์ชันแสดง Summary Statistics และ Frequencies

–> Functions for displaying summary statistics and frequencies

Input Datasets

  • nls97f.csv – The survey started with a cohort of individuals in 1997 who were born between 1980 and 1985, with annual follow-ups each year through 2017. the National Longitudinal Survey (NLS) 1997-2017.

Question 12: สร้างฟังก์ชัน getmissings, gettots, makefreqs และ getcnts เพิ่มเติมต้องเขียนอย่างไรบ้าง?

STEP 1: นำเข้า Datasets โดยทำการ Upload ไฟล์ nls97f.csv ขึ้น Google Colab (ไฟล์นี้จะถูกลบเมื่อเราหลุดจาก Session หรือปิด Browser) หรือ Python IDE เช่น PyCharm, VSCode, Juputer Notebook, etc.

STEP 2: เขียนโปรแกรมเพื่อสร้างฟังก์ชันต่าง ๆ รวม 6 functions

#Define Functions
#(1) get first look
def getfirstlook(df, nrows=5, uniqueids=None):
  out = {}
  out['head'] = df.head(nrows)
  out['dtypes'] = df.dtypes
  out['nrows'] = df.shape[0]
  out['ncols'] = df.shape[1]
  out['index'] = df.index
  if (uniqueids is not None):
    out['uniqueids'] = df[uniqueids].nunique()
  return out

#(2) displaydict
def displaydict(dicttodisplay):
  print(*(': '.join(map(str, x)) \
    for x in dicttodisplay.items()), sep='\n\n')

#(3) get summary statistics
def gettots(df):
  out = {}
  out['min'] = df.min()
  out['per15'] = df.quantile(0.15)
  out['qr1'] = df.quantile(0.25)
  out['med'] = df.median()
  out['qr3'] = df.quantile(0.75)
  out['per85'] = df.quantile(0.85)
  out['max'] = df.max()
  out['count'] = df.count()
  out['mean'] = df.mean()
  out['iqr'] = out['qr3']-out['qr1']
  return pd.DataFrame(out)

#(4) count missings by columns and rows
def getmissings(df, byrowperc=False):
  return df.isnull().sum(),\
    df.isnull().sum(axis=1).value_counts(normalize=byrowperc).sort_index()

#(5) do frequencies and percentages for all category variables in data frame
def makefreqs(df, outfile):
  freqout = open(outfile, 'w') 
  for col in df.select_dtypes(include=["category"]):
    print(col, "----------------------", "frequencies",
    df[col].value_counts().sort_index(),"percentages",
    df[col].value_counts(normalize=True).sort_index(),
    sep="\n\n", end="\n\n\n", file=freqout)

  freqout.close()

#(6) get counts by groupings
def getcnts(df, cats, rowsel=None):
  tots = cats[:-1]
  catcnt = df.groupby(cats).size().reset_index(name='catcnt')
  totcnt = df.groupby(tots).size().reset_index(name='totcnt')
  percs = pd.merge(catcnt, totcnt, left_on=tots, 
    right_on=tots, how="left")
  percs['percent'] = percs.catcnt / percs.totcnt
  if (rowsel is not None):
    percs = percs.loc[eval("percs." + rowsel)]
  return percs

STEP 3: นำเข้า pandas librariey มาใช้งาน

STEP 4: ทำการอ่านไฟล์ .csv ด้วย pandas เก็บเป็น Dataframe

ใช้คำสั่ง .read_csv()

STEP 5: ตั้งค่าและแสดง index และ size ของ nls97f data

ใช้คำสั่ง set_index()

#import pandas library
import pandas as pd
nls97 = pd.read_csv("/content/nls97f.csv")
print(nls97)
nls97.set_index('personid', inplace=True)
print(nls97)
personid  gender  birthmonth  ...      colenrfeb17      colenroct17 originalid
0       100061  Female           5  ...  1. Not enrolled  1. Not enrolled       8245
1       100139    Male           9  ...  1. Not enrolled  1. Not enrolled       3962
2       100284    Male          11  ...  1. Not enrolled  1. Not enrolled       3571
3       100292    Male           4  ...              NaN              NaN       2979
4       100583    Male           1  ...  1. Not enrolled  1. Not enrolled       8511
...        ...     ...         ...  ...              ...              ...        ...
8979    999291  Female           4  ...  1. Not enrolled  1. Not enrolled       7217
8980    999406    Male           7  ...  1. Not enrolled  1. Not enrolled          2
8981    999543  Female           8  ...  1. Not enrolled  1. Not enrolled       5113
8982    999698  Female           5  ...  1. Not enrolled  1. Not enrolled       7815
8983    999963  Female           9  ...  1. Not enrolled  1. Not enrolled        166

[8984 rows x 90 columns]
          gender  birthmonth  ...      colenroct17  originalid
personid                      ...                             
100061    Female           5  ...  1. Not enrolled        8245
100139      Male           9  ...  1. Not enrolled        3962
100284      Male          11  ...  1. Not enrolled        3571
100292      Male           4  ...              NaN        2979
100583      Male           1  ...  1. Not enrolled        8511
...          ...         ...  ...              ...         ...
999291    Female           4  ...  1. Not enrolled        7217
999406      Male           7  ...  1. Not enrolled           2
999543    Female           8  ...  1. Not enrolled        5113
999698    Female           5  ...  1. Not enrolled        7815
999963    Female           9  ...  1. Not enrolled         166

[8984 rows x 89 columns]

STEP 6: เรียกใช้ฟังก์ชัน gettots() เพื่อแสดงค่า summary statistcs

#show summary statistics for continuous variables
print(gettots(nls97[['satverbal','satmath']]).T)
print()
print(gettots(nls97.filter(like="weeksworked")))  #Filter เอาเฉพาะ columns ที่มีชื่อคำว่า weeksworked
 satverbal      satmath
min      14.00000     7.000000
per15   390.00000   390.000000
qr1     430.00000   430.000000
med     500.00000   500.000000
qr3     570.00000   580.000000
per85   620.00000   621.000000
max     800.00000   800.000000
count  1406.00000  1407.000000
mean    499.72404   500.590618
iqr     140.00000   150.000000

               min  per15   qr1   med  ...   max  count       mean   iqr
weeksworked00  0.0    0.0   5.0  26.0  ...  53.0   8603  26.417761  45.0
weeksworked01  0.0    0.0  10.0  33.0  ...  52.0   8564  29.784096  41.0
weeksworked02  0.0    0.0  13.0  38.0  ...  52.0   8556  31.805400  39.0
weeksworked03  0.0    0.0  14.0  43.0  ...  52.0   8490  33.469611  38.0
weeksworked04  0.0    1.0  18.0  46.0  ...  52.0   8458  35.104635  34.0
weeksworked05  0.0    5.0  22.0  50.0  ...  53.0   8403  37.316435  31.0
weeksworked06  0.0    9.0  27.0  51.0  ...  52.0   8340  38.429976  25.0
weeksworked07  0.0   10.0  30.0  52.0  ...  52.0   8272  39.241296  22.0
weeksworked08  0.0    9.0  30.0  52.0  ...  52.0   8186  39.287564  22.0
weeksworked09  0.0    0.0  22.0  52.0  ...  52.0   8146  37.419961  30.0
weeksworked10  0.0    0.0  20.0  52.0  ...  52.0   8054  37.029923  32.0
weeksworked11  0.0    0.0  22.0  53.0  ...  53.0   7968  37.911270  31.0
weeksworked12  0.0    0.0  22.0  52.0  ...  52.0   7747  38.036918  30.0
weeksworked13  0.0    0.0  28.0  52.0  ...  52.0   7680  38.791016  24.0
weeksworked14  0.0    0.0  23.0  52.0  ...  52.0   7612  38.316999  29.0
weeksworked15  0.0    0.0  33.0  52.0  ...  52.0   7389  39.605630  19.0
weeksworked16  0.0    0.0  23.0  53.0  ...  53.0   7068  39.127476  30.0
weeksworked17  0.0    0.0  37.0  49.0  ...  52.0   6670  39.016642  15.0

[18 rows x 10 columns]

STEP 7: เรียกใช้ฟังก์ชัน getmissings() เพื่อนับจำนวน missing data ต่อ column และต่อ row

#count missing per column and per row
missingsbycols, missingsbyrows = getmissings(nls97[['weeksworked16','weeksworked17']])
print(missingsbycols)
print()
print(missingsbyrows)
weeksworked16    1916
weeksworked17    2314
dtype: int64

0    6641
1     456
2    1887
dtype: int64

STEP 8: เรียกใช้ฟังก์ชัน makefreqs เพื่อรับความถี่ของ categorical columns

#do frequencies for categorical columns
#แปลง data types จาก object ให้เป็น category
nls97.loc[:, nls97.dtypes == 'object'] = \
  nls97.select_dtypes(['object']). \
  apply(lambda x: x.astype('category'))
#เรียกใช้ฟังก์ชัน makefreqs เขียนไฟล์แสดงจำนวนความถี่ที่นับได้
makefreqs(nls97, "/content/nlsfreqs.txt")

STEP 9: เรียกใช้ฟังก์ชัน getcnts นับจำนวนและ % ตาม groups

#do counts and percentages by groups
print(getcnts(nls97, ['maritalstatus','gender','colenroct00']))
print()
print(getcnts(nls97, ['maritalstatus','gender','colenroct00'], "colenroct00.str[0:1]=='1'"))
maritalstatus  gender         colenroct00  catcnt  totcnt   percent
0        Divorced  Female     1. Not enrolled     317     393  0.806616
1        Divorced  Female  2. 2-year college       35     393  0.089059
2        Divorced  Female   3. 4-year college      41     393  0.104326
3        Divorced    Male     1. Not enrolled     238     270  0.881481
4        Divorced    Male  2. 2-year college       15     270  0.055556
5        Divorced    Male   3. 4-year college      17     270  0.062963
6         Married  Female     1. Not enrolled    1168    1636  0.713936
7         Married  Female  2. 2-year college      143    1636  0.087408
8         Married  Female   3. 4-year college     325    1636  0.198655
9         Married    Male     1. Not enrolled    1094    1430  0.765035
10        Married    Male  2. 2-year college       93    1430  0.065035
11        Married    Male   3. 4-year college     243    1430  0.169930
12  Never-married  Female     1. Not enrolled    1094    1307  0.837031
13  Never-married  Female  2. 2-year college       65    1307  0.049732
14  Never-married  Female   3. 4-year college     148    1307  0.113236
15  Never-married    Male     1. Not enrolled    1268    1459  0.869088
16  Never-married    Male  2. 2-year college       66    1459  0.045236
17  Never-married    Male   3. 4-year college     125    1459  0.085675
18      Separated  Female     1. Not enrolled      66      79  0.835443
19      Separated  Female  2. 2-year college        8      79  0.101266
20      Separated  Female   3. 4-year college       5      79  0.063291
21      Separated    Male     1. Not enrolled      67      75  0.893333
22      Separated    Male  2. 2-year college        5      75  0.066667
23      Separated    Male   3. 4-year college       3      75  0.040000
24        Widowed  Female     1. Not enrolled      16      19  0.842105
25        Widowed  Female  2. 2-year college        1      19  0.052632
26        Widowed  Female   3. 4-year college       2      19  0.105263
27        Widowed    Male     1. Not enrolled       3       4  0.750000
28        Widowed    Male  2. 2-year college        0       4  0.000000
29        Widowed    Male   3. 4-year college       1       4  0.250000

    maritalstatus  gender      colenroct00  catcnt  totcnt   percent
0        Divorced  Female  1. Not enrolled     317     393  0.806616
3        Divorced    Male  1. Not enrolled     238     270  0.881481
6         Married  Female  1. Not enrolled    1168    1636  0.713936
9         Married    Male  1. Not enrolled    1094    1430  0.765035
12  Never-married  Female  1. Not enrolled    1094    1307  0.837031
15  Never-married    Male  1. Not enrolled    1268    1459  0.869088
18      Separated  Female  1. Not enrolled      66      79  0.835443
21      Separated    Male  1. Not enrolled      67      75  0.893333
24        Widowed  Female  1. Not enrolled      16      19  0.842105
27        Widowed    Male  1. Not enrolled       3       4  0.750000

Workshop 13: สร้าง Class และเรียกใช้งาน Functions เพื่อทำความสะอาดข้อมูล

–> Classes that contain the logic for updating series values

Input Datasets

  • nls97f.csv – The survey started with a cohort of individuals in 1997 who were born between 1980 and 1985, with annual follow-ups each year through 2017. the National Longitudinal Survey (NLS) 1997-2017.

Question 13: สร้าง Class เพื่อเรียกใช้งาน functions ต่าง ๆ ต้องเขียนอย่างไรบ้าง?

STEP 1: นำเข้า Datasets โดยทำการ Upload ไฟล์ nls97f.csv ขึ้น Google Colab (ไฟล์นี้จะถูกลบเมื่อเราหลุดจาก Session หรือปิด Browser) หรือ Python IDE เช่น PyCharm, VSCode, Juputer Notebook, etc.

STEP 2: เขียนโปรแกรมเพื่อสร้าง Class และ functions ต่าง ๆ ที่อยู่ภายใน Class

import math
import datetime as dt

class Respondent:
  respondentcnt = 0
  #(1) Constructure ต้องมีทุก Class สำหรับกำหนดค่าเริ่มต้นของคลาส
  def __init__(self, respdict):
    self.respdict = respdict
    Respondent.respondentcnt+=1
   
  #(2) add the number of children at home and not at home
  def childnum(self):
    return self.respdict['childathome'] + self.respdict['childnotathome']

  #(3) select the weeksworked## keys and calcuate the average of their values
  def avgweeksworked(self):
    workdict = {k: v for k, v in self.respdict.items() \
      if k.startswith('weeksworked') and not math.isnan(v)}
    nweeks = len(workdict)
    if (nweeks>0):
      avgww = sum(workdict.values())/nweeks
    else:
      avgww = 0
    return avgww

  #(4) define a function for calculating given start and end date
  def ageby(self, bydatestring):
    bydate = dt.datetime.strptime(bydatestring, '%Y%m%d')
    birthyear = self.respdict['birthyear']
    birthmonth = self.respdict['birthmonth']
    age = bydate.year - birthyear
    if (bydate.month<birthmonth or (bydate.month==birthmonth \
        and bydate.day<15)):
      age = age -1
    return age
  
  #(5) define baenrollment function
  def baenrollment(self):
    colenrdict = {k: v for k, v in self.respdict.items() \
      if k.startswith('colenr') and v=="3. 4-year college"}
    if (len(colenrdict)>0):
      return "Y"
    else:
      return "N"

STEP 3: นำเข้า pandas librariey มาใช้งาน

STEP 4: ทำการอ่านไฟล์ .csv ด้วย pandas เก็บเป็น Dataframe

ใช้คำสั่ง .read_csv()

STEP 5: ตั้งค่าและแสดง index และ size ของ nls97f data

ใช้คำสั่ง set_index()

#import the pandas and pprint libraries
import pandas as pd
import pprint
#load the NLS data and then create a list of dictionaries
nls97 = pd.read_csv("/content/nls97f.csv")
nls97list = nls97.to_dict('records')  #คำสั่ง .to_dict() เป็นการ Convert the DataFrame to a dictionary.
print(nls97.shape)
print()
print(len(nls97list))
print()
pprint.pprint(nls97list[0:1])
(8984, 90)

8984

[{'birthmonth': 5,
  'birthyear': 1980,
  'childathome': 4.0,
  'childnotathome': 0.0,
  'colenrfeb00': '1. Not enrolled',
  'colenrfeb01': '1. Not enrolled',
  'colenrfeb02': '1. Not enrolled',
  'colenrfeb03': '1. Not enrolled',
  'colenrfeb04': '1. Not enrolled',
  'colenrfeb05': '1. Not enrolled',
  'colenrfeb06': '1. Not enrolled',
  'colenrfeb07': '1. Not enrolled',
  'colenrfeb08': '1. Not enrolled',
  'colenrfeb09': '1. Not enrolled',
  'colenrfeb10': '1. Not enrolled',
  'colenrfeb11': '1. Not enrolled',
  'colenrfeb12': '3. 4-year college',
  'colenrfeb13': '1. Not enrolled',
  'colenrfeb14': '1. Not enrolled',
  'colenrfeb15': '1. Not enrolled',
  'colenrfeb16': '1. Not enrolled',
  'colenrfeb17': '1. Not enrolled',
  'colenrfeb97': '1. Not enrolled',
  'colenrfeb98': '1. Not enrolled',
  'colenrfeb99': '1. Not enrolled',
  'colenroct00': '1. Not enrolled',
  'colenroct01': '1. Not enrolled',
  'colenroct02': '1. Not enrolled',
  'colenroct03': '1. Not enrolled',
  'colenroct04': '1. Not enrolled',
  'colenroct05': '1. Not enrolled',
  'colenroct06': '1. Not enrolled',
  'colenroct07': '1. Not enrolled',
  'colenroct08': '1. Not enrolled',
  'colenroct09': '1. Not enrolled',
  'colenroct10': '1. Not enrolled',
  'colenroct11': '3. 4-year college',
  'colenroct12': '3. 4-year college',
  'colenroct13': '1. Not enrolled',
  'colenroct14': '1. Not enrolled',
  'colenroct15': '1. Not enrolled',
  'colenroct16': '1. Not enrolled',
  'colenroct17': '1. Not enrolled',
  'colenroct97': '1. Not enrolled',
  'colenroct98': '1. Not enrolled',
  'colenroct99': '1. Not enrolled',
  'gender': 'Female',
  'govcollegefinance': nan,
  'govdecenthousing': nan,
  'govelderliving': nan,
  'govhealthcare': nan,
  'govincomediff': nan,
  'govindhelp': nan,
  'govpricecontrols': nan,
  'govprotectenvironment': nan,
  'govprovidejobs': nan,
  'govunemp': nan,
  'gpaenglish': 350.0,
  'gpamath': 280.0,
  'gpaoverall': 306.0,
  'gpascience': 315.0,
  'highestdegree': '2. High School',
  'highestgradecompleted': 13.0,
  'maritalstatus': 'Married',
  'nightlyhrssleep': 6.0,
  'originalid': 8245,
  'personid': 100061,
  'satmath': nan,
  'satverbal': nan,
  'wageincome': 12500.0,
  'weeklyhrscomputer': '10 hours or more a week',
  'weeklyhrstv': '11 to 20 hours a week',
  'weeksworked00': 46.0,
  'weeksworked01': 52.0,
  'weeksworked02': 52.0,
  'weeksworked03': 48.0,
  'weeksworked04': 52.0,
  'weeksworked05': 53.0,
  'weeksworked06': 52.0,
  'weeksworked07': 52.0,
  'weeksworked08': 39.0,
  'weeksworked09': 40.0,
  'weeksworked10': 52.0,
  'weeksworked11': 53.0,
  'weeksworked12': 40.0,
  'weeksworked13': 52.0,
  'weeksworked14': 52.0,
  'weeksworked15': 52.0,
  'weeksworked16': 48.0,
  'weeksworked17': 48.0}]

STEP 6: เปิดใช้งาน Class ชื่อ Respondent() และใช้งาน functions ต่าง ๆ ที่อยู่ใน Class

#loop through the list creating a respondent instance each time
analysislist = []
for respdict in nls97list:
  resp = Respondent(respdict) #เปิดใช้งาน class(ใส่ตาม constructure)
  newdict = dict(originalid=respdict['originalid'],
    childnum=resp.childnum(),
    avgweeksworked=resp.avgweeksworked(),
    age=resp.ageby('20201015'),
    baenrollment=resp.baenrollment())
  analysislist.append(newdict)

STEP 7: สร้าง pandas DataFrame

#create a pandas data frame
len(analysislist)
resp.respondentcnt
pprint.pprint(analysislist[0:4])
analysis = pd.DataFrame(analysislist)
print()
print(analysis.head(4))
[{'age': 40,
  'avgweeksworked': 49.05555555555556,
  'baenrollment': 'Y',
  'childnum': 4.0,
  'originalid': 8245},
 {'age': 37,
  'avgweeksworked': 49.388888888888886,
  'baenrollment': 'N',
  'childnum': 2.0,
  'originalid': 3962},
 {'age': 35,
  'avgweeksworked': 28.176470588235293,
  'baenrollment': 'N',
  'childnum': 1.0,
  'originalid': 3571},
 {'age': 38,
  'avgweeksworked': 43.35294117647059,
  'baenrollment': 'Y',
  'childnum': nan,
  'originalid': 2979}]

   originalid  childnum  avgweeksworked  age baenrollment
0        8245       4.0       49.055556   40            Y
1        3962       2.0       49.388889   37            N
2        3571       1.0       28.176471   35            N
3        2979       NaN       43.352941   38            Y

Practice 4: สร้างภาพข้อมูล

Python Data Visualization

Python Pandas Cheat Sheets

Workshop 14: การใช้แผนภาพเส้นเพื่อตรวจสอบแนวโน้มในตัวแปรต่อเนื่อง

–> Using line plots to examine trends in continuous variables

Input Datasets

Question 14: เราจะสร้างภาพข้อมูลได้อย่างไรบ้าง?

STEP 1: นำเข้า Datasets โดยทำการ Upload ไฟล์ coviddaily720.csv ขึ้น Google Colab (ไฟล์นี้จะถูกลบเมื่อเราหลุดจาก Session หรือปิด Browser) หรือ Python IDE เช่น PyCharm, VSCode, Juputer Notebook, etc.

STEP 2: นำเข้า pandas, numpy และ matplotlib libraries มาใช้งาน

STEP 3: ทำการอ่านไฟล์ .csv ด้วย pandas เก็บเป็น Dataframe

ใช้คำสั่ง .read_csv() pasrse_dates=[ “colunm_name” ] เป็น data type ชนิด datetime

#import pandas, numpy, and matplotlib
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.dates import DateFormatter
coviddaily = pd.read_csv("/content/coviddaily720.csv", parse_dates=["casedate"])

STEP 4: ทำการสุ่มกลุ่มตัวอย่าง

ใช้คำสั่ง sample()

#look at a couple of sample rows of the covid daily data
print(coviddaily.sample(2, random_state=1).T)
2478                 9526
iso_code                        BRB                  FRA
casedate        2020-06-11 00:00:00  2020-02-16 00:00:00
location                   Barbados               France
continent             North America               Europe
new_cases                         4                    0
new_deaths                        0                    0
population                   287371          6.52735e+07
pop_density                 664.463              122.578
median_age                     39.8                   42
gdp_per_capita              16978.1              38605.7
hosp_beds                       5.8                 5.98
region                    Caribbean       Western Europe

STEP 5: แสดงการคำนวณ

#calculate new cases and deaths by day
coviddailytotals = coviddaily.loc[coviddaily.casedate.between('2020-02-01','2020-07-12')].\
  groupby(['casedate'])[['new_cases','new_deaths']].\
  sum().\
  reset_index()
print(coviddailytotals)
casedate  new_cases  new_deaths
0   2020-02-01     2120.0        46.0
1   2020-02-02     2608.0        46.0
2   2020-02-03     2818.0        57.0
3   2020-02-04     3243.0        65.0
4   2020-02-05     3897.0        66.0
..         ...        ...         ...
158 2020-07-08   207024.0      6091.0
159 2020-07-09   215473.0      5375.0
160 2020-07-10   228608.0      5441.0
161 2020-07-11   229759.0      5276.0
162 2020-07-12   222967.0      4926.0

[163 rows x 3 columns]

STEP 6: สุ่มกลุ่มตัวอย่าง

print(coviddailytotals.sample(7, random_state=1))
casedate  new_cases  new_deaths
44  2020-03-16    12386.0       757.0
47  2020-03-19    20130.0       961.0
94  2020-05-05    77474.0      3998.0
78  2020-04-19    80127.0      6005.0
160 2020-07-10   228608.0      5441.0
11  2020-02-12     2033.0        97.0
117 2020-05-28   102619.0      5168.0

STEP 7: แสดงการสร้างภาพข้อมูล Line Charts

#show line charts for new cases and new deaths by day
fig = plt.figure()
plt.suptitle("New Covid Cases and Deaths By Day Worldwide in 2020")
ax1 = plt.subplot(2,1,1) #วาดรูปพื้นที่ 2 แถว 1 คอลัมน์ index ตำแหน่งที่ 1
ax1.plot(coviddailytotals.casedate, coviddailytotals.new_cases)
#%b ชื่อย่อของเดือน %B ชื่อเต็มของเดือน
ax1.xaxis.set_major_formatter(DateFormatter("%b"))
ax1.set_xlabel("New Cases")
ax2 = plt.subplot(2,1,2) #วาดรูปพื้นที่ 2 แถว 1 คอลัมน์ index ตำแหน่งที่ 1
ax2.plot(coviddailytotals.casedate, coviddailytotals.new_deaths)
ax2.xaxis.set_major_formatter(DateFormatter("%b"))
ax2.set_xlabel("New Deaths")
plt.tight_layout()   #ปรับขนาดให้ตัวอักษรไม่ทับกันโดยอัตโนมัติ
fig.subplots_adjust(top=0.88)
plt.show()

STEP 8: แสดงการคำนวณ

#calculate new cases and new deaths by region and day
regiontotals = coviddaily.loc[coviddaily.casedate.between('2020-02-01','2020-07-12')].\
  groupby(['casedate','region'])[['new_cases','new_deaths']].\
  sum().\
  reset_index()
print(regiontotals)
print(regiontotals.sample(7, random_state=1))
casedate           region  new_cases  new_deaths
0    2020-02-01        Caribbean        0.0         0.0
1    2020-02-01     Central Asia        0.0         0.0
2    2020-02-01        East Asia     2110.0        46.0
3    2020-02-01   Eastern Europe        2.0         0.0
4    2020-02-01     North Africa        0.0         0.0
...         ...              ...        ...         ...
2434 2020-07-12       South Asia    34534.0       674.0
2435 2020-07-12  Southern Africa    13857.0       118.0
2436 2020-07-12      West Africa     1922.0        19.0
2437 2020-07-12        West Asia    13378.0       349.0
2438 2020-07-12   Western Europe     2375.0       169.0

[2439 rows x 4 columns]
       casedate          region  new_cases  new_deaths
1518 2020-05-16    North Africa      634.0        28.0
2410 2020-07-11    Central Asia     3873.0        26.0
870  2020-04-05  Western Europe    30090.0      4079.0
1894 2020-06-08  Western Europe     3712.0       180.0
790  2020-03-31  Western Europe    30180.0      2970.0
2270 2020-07-02    North Africa     2006.0        89.0
306  2020-02-26   Oceania / Aus        0.0         0.0

STEP 9: แสดงการสร้างภาพข้อมูล

#show plot of new cases by selected regions
showregions = ['East Asia','Southern Africa','North America',
  'Western Europe']
for j in range(len(showregions)):
  rt = regiontotals.loc[regiontotals.region==showregions[j],
    ['casedate','new_cases']]
  plt.plot(rt.casedate, rt.new_cases, label=showregions[j])
plt.title("New Covid Cases By Day and Region in 2020")
#.gca() get current axes เอาไว้ปรับแต่งค่าต่าง ๆ ในแกน
plt.gca().get_xaxis().set_major_formatter(DateFormatter("%b"))
plt.ylabel("New Cases")
plt.legend()
plt.show()

at GlurGeek.Com
Lecturer, Blogger, Traveler, and Software Developer ที่ชอบอ่านบทความใหม่ๆ ตลอดเวลา ชอบหาวิธีสร้าง Inspiration เป็นชีวิตจิตใจ มีความฝันอยากทำ CREATIVE PRODUCT ที่สามารถเปลี่ยนแปลงโลกให้ดีขึ้น และอยากถ่ายรูปสถานที่ท่องเที่ยวรอบโลก สอนหนังสือ ชอบแลกเปลี่ยนความรู้ และเขียน WEBSITE, MOBILE APP, GAME, ETC ที่เป็นประโยชน์กับโลกใบนี้

Leave a Reply

© 2022 GlurGeek.Com
Exit mobile version