Python มีไลบรารีวิเคราะห์และแสดงข้อมูลมากมาย: NumPy, Pandas, Matplotlib, Seaborn บทความนี้เน้น Pandas ไลบรารีโอเพนซอร์สบน NumPy ทำ Data Analysis และ Visualization ได้รวดเร็ว
การติดตั้ง
pip install pandas
# หรือ
conda install pandas
Pandas DataFrames
DataFrame คือเครื่องมือหลักของ Pandas
import numpy as np
import pandas as pd
from numpy.random import randn
np.random.seed(50)
df = pd.DataFrame(randn(6,4), ['a','b','c','d','e','f'], ['w','x','y','z'])
df
ผลลัพธ์
| w | x | y | z | |
|---|---|---|---|---|
| a | -1.560352 | -0.030978 | -0.620928 | -1.464580 |
| b | 1.411946 | -0.476732 | -0.780469 | 1.070268 |
| c | -1.282293 | -1.327479 | 0.126338 | 0.862194 |
| d | 0.696737 | -0.334565 | -0.997526 | 1.598908 |
| e | 3.314075 | 0.987770 | 0.123866 | 0.742785 |
| f | -0.393956 | 0.148116 | -0.412234 | -0.160715 |
จัดการ Missing Data
import numpy as np
import pandas as pd
d = {'A': [1,2,np.nan], 'B': [9, np.nan, np.nan], 'C': [1,4,9]}
df = pd.DataFrame(d)
df
ผลลัพธ์ (มี NaN 3 ค่า)
| A | B | C | |
|---|---|---|---|
| 0 | 1.0 | 9.0 | 1 |
| 1 | 2.0 | NaN | 4 |
| 2 | NaN | NaN | 9 |
วิธีจัดการ Missing Values
df.dropna() # ลบแถวที่มี NaN
df.dropna(axis=1) # ลบคอลัมน์ที่มี NaN
df.dropna(thresh=2) # เก็บแถวที่มี non-NaN อย่างน้อย 2 ค่า
df.fillna(value=df.mean()) # เติม NaN ด้วยค่าเฉลี่ยคอลัมน์
นำเข้าข้อมูล (Import Data)
import pandas as pd
df = pd.read_csv("data.csv", encoding="ISO-8859-1")
df.head() # 5 แถวแรก
df.shape # (rows, columns)
ผลลัพธ์ df.shape
(4166, 9)
DataFrame Math และ Statistics
df.describe() # สถิติพื้นฐาน (count, mean, std, min, max, quartiles)
df.rank() # อันดับของข้อมูลตัวเลข
Visualization ด้วย Pandas + Matplotlib
Line Plot
import matplotlib.pyplot as plt
years = [1981, 1991, 2001, 2011, 2016]
populations = [716493000, 891910000, 1071374000, 1197658000, 1273986000]
plt.plot(years, populations)
plt.title("Census of India: Sample Registration System")
plt.xlabel("Year")
plt.ylabel("Average Population")
plt.show()
Scatter Plot
plt.scatter(years, populations)
plt.show()
Histogram
plt.hist(populations, bins=10)
plt.xlabel("Average Population")
plt.ylabel("Frequency")
plt.show()
สรุปความสามารถ Pandas
- อ่าน/เขียนไฟล์: CSV, Excel, JSON, SQL, HDF5, Parquet
- Data Cleaning: dropna, fillna, replace, astype
- Transform: groupby, pivot_table, melt, merge, join
- Time Series: resample, rolling, shift, datetime handling
- Visualization: df.plot(), df.hist(), df.boxplot(), df.scatter_matrix()
- Performance: Vectorized operations, Cython backend
Pandas เป็นหัวใจของ Data Science ใน Python ควบคู่กับ NumPy และ Matplotlib