Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Data Analysis และ Visualization ใน Python ด้วย Pandas

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

ผลลัพธ์

wxyz
a-1.560352-0.030978-0.620928-1.464580
b1.411946-0.476732-0.7804691.070268
c-1.282293-1.3274790.1263380.862194
d0.696737-0.334565-0.9975261.598908
e3.3140750.9877700.1238660.742785
f-0.3939560.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 ค่า)

ABC
01.09.01
12.0NaN4
2NaNNaN9

วิธีจัดการ 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