Xử lý và phân tích dữ liệu với Pandas: Từ Excel đến báo cáo
Mục lục bài viết
1. Pandas là gì?
Pandas là thư viện Python mã nguồn mở chuyên xử lý dữ liệu dạng bảng (tabular data).
Nó cung cấp hai cấu trúc dữ liệu chính: Series (1 chiều) và DataFrame (2 chiều, giống bảng Excel).
Cài đặt: pip install pandas
So sánh Pandas vs Excel:
- Excel: 1 triệu dòng giới hạn.
Pandas: xử lý hàng trăm triệu dòng.
- Excel: Thao tác thủ công, khó tái lập.
Pandas: Script có thể chạy lại.
- Excel: Chậm với file lớn.
Pandas: Xử lý nhanh hơn 10-100x.
- Excel: Khó tích hợp vào pipeline.
Pandas: Kết nối database, API dễ dàng.
2. Đọc và xem dữ liệu
Đọc file CSV:
import pandas as pd
df = pd.read_csv('sales.csv')
Đọc Excel:
df = pd.read_excel('report.xlsx', sheet_name='Sheet1')
Đọc từ database:
import sqlite3
conn = sqlite3.connect('data.db')
df = pd.read_sql('SELECT * FROM users', conn)
Xem dữ liệu nhanh:
df.head(10)- 10 dòng đầu.df.tail(5)- 5 dòng cuối.df.info()- Thông tin: cột, kiểu dữ liệu, null count.df.describe()- Thống kê cơ bản (mean, std, min, max).df.shape- (số dòng, số cột).df.columns- Danh sách tên cột.
df.head() trước khi làm gì đó: luôn kiểm tra dữ liệu trước khi xử lý.3. Làm sạch dữ liệu (Data Cleaning)
Xử lý giá trị null:
df.dropna()- Xoá dòng có null.df.fillna(0)- Thay null bằng 0.df.fillna(df.mean())- Thay null bằng giá trị trung bình.df['column'].fillna(method='ffill')- Forward fill.
Xoá dòng trùng:
df.drop_duplicates()
Đổi tên cột:
df.rename(columns={'old_name': 'new_name'}, inplace=True)
Chuyển đổi kiểu dữ liệu:
df['date'] = pd.to_datetime(df['date'])
df['price'] = df['price'].astype(float)
Lọc dữ liệu theo điều kiện:
high_sales = df[df['revenue'] > 10000]filtered = df[(df['city'] == 'Hanoi') & (df['sales'] > 50)]
4. Phân tích và nhóm dữ liệu
GroupBy: Nhóm và tính toán:
df.groupby('category')['revenue'].sum()
df.groupby(['city', 'month'])['sales'].agg(['sum', 'mean', 'count'])
Pivot Table:
pd.pivot_table(df, values='revenue', index='city', columns='year', aggfunc='sum')
Apply: Áp dụng function lên cột:
df['discounted'] = df['price'].apply(lambda x: x * 0.9)
Sort:
df.sort_values('revenue', ascending=False)
Merge và Join (giống VLOOKUP):
merged = pd.merge(df_orders, df_customers, on='customer_id', how='left')
merge mạnh hơn VLOOKUP: có thể inner, left, right, outer join. Học merge là bạn làm chủ data joining.5. Xuất dữ liệu và báo cáo
Xuất ra CSV:
df.to_csv('output.csv', index=False)
Xuất ra Excel (nhiều sheet):
with pd.ExcelWriter('report.xlsx') as writer:
df_summary.to_excel(writer, sheet_name='Summary')
df_detail.to_excel(writer, sheet_name='Detail')
Xuất ra JSON:
df.to_json('data.json', orient='records', force_ascii=False)
Xuất ra HTML (báo cáo web):
df.to_html('report.html')
index=False ngăn Pandas xuất dòng số (index) ra file. Luôn dùng khi xuất để clean output.6. Vẽ biểu đồ nhanh với Pandas + Matplotlib
Pandas tích hợp sẵn Matplotlib để vẽ biểu đồ nhanh.
import matplotlib.pyplot as plt
Line chart (xu hướng):
df.groupby('month')['revenue'].sum().plot(kind='line')
plt.show()
Bar chart (so sánh):
df.groupby('category')['sales'].sum().plot(kind='bar')
Histogram (phân phối):
df['age'].plot(kind='hist', bins=20)
Box plot (outliers):
df.boxplot(column='price', by='category')
plt.savefig('chart.png', dpi=300) để lưu biểu đồ. Hoặc dùng Seaborn (sns) cho biểu đồ đẹp hơn.7. Lam viec voi datetime trong Pandas
Pandas xu ly ngay thang rat manh voi pd.to_datetime.
Chuyen cot string thanh datetime: df['date'] = pd.to_datetime(df['date']).
Sau do ban co the truy cap: df['date'].dt.year, .dt.month, .dt.day, .dt.dayofweek.
Resample theo thoi gian:
df.resample('M', on='date')['revenue'].sum() - Tinh tong doanh thu theo thang.
df.resample('Q', on='date')['revenue'].mean() - Theo quy.
Date range:
pd.date_range(start='2026-01-01', end='2026-12-31', freq='D') - Tao chuoi ngay.
df.set_index('date', inplace=True). Viec nay giup resample va slicing theo thoi gian nhanh hon.🙋 Câu hỏi thường gặp
Pandas có miễn phí không?
Có. Pandas là mã nguồn mở (BSD license), miễn phí cho mọi mục đích: cá nhân, giáo dục, thương mại.
Pandas có xử lý được file 10GB không?
Có thể nhưng cần kỹ thuật: pd.read_csv('file.csv', chunksize=10000) đọc từng chunk, hoặc dùng Dask cho big data. Với file > 1GB, nên dùng dtype để tối ưu bộ nhớ.
Nên học Pandas hay Excel formulas trước?
Cả hai. Excel tốt cho ad-hoc analysis nhanh (vài trăm dòng). Pandas cần thiết cho automation, big data, và reproducibility. Học Pandas nếu bạn muốn làm data chuyên nghiệp.