Pandas - Xử Lý Dữ Liệu
1. Giới thiệu Pandas
Pandas là thư viện xử lý dữ liệu #1 trong Python, cung cấp:
- DataFrame: Bảng 2D (giống Excel/SQL table)
- Series: Mảng 1D với labels
Python
1import pandas as pd2import numpy as np34# Kiểm tra version5print(pd.__version__) # 2.x.x2. Tạo DataFrame
2.1 Từ Dictionary
Python
1# Từ dict2data = {3 "name": ["Alice", "Bob", "Charlie"],4 "age": [25, 30, 35],5 "city": ["Hanoi", "HCMC", "Danang"]6}7df = pd.DataFrame(data)89# name age city10# 0 Alice 25 Hanoi11# 1 Bob 30 HCMC12# 2 Charlie 35 Danang2.2 Từ List of Dicts
Python
1data = [2 {"name": "Alice", "age": 25},3 {"name": "Bob", "age": 30},4 {"name": "Charlie", "age": 35}5]6df = pd.DataFrame(data)2.3 Từ File
Python
1# CSV2df = pd.read_csv("data.csv")3df = pd.read_csv("data.csv", sep=";", encoding="utf-8")45# Excel6df = pd.read_excel("data.xlsx", sheet_name="Sheet1")78# JSON9df = pd.read_json("data.json")1011# SQL12import sqlite313conn = sqlite3.connect("database.db")14df = pd.read_sql("SELECT * FROM users", conn)1516# Parquet (hiệu quả cho big data)17df = pd.read_parquet("data.parquet")3. Khám Phá Dữ Liệu
3.1 Xem tổng quan
Python
1# Kích thước2df.shape # (rows, columns)34# Xem dữ liệu5df.head() # 5 dòng đầu6df.head(10) # 10 dòng đầu7df.tail() # 5 dòng cuối8df.sample(5) # 5 dòng random910# Thông tin11df.info() # Kiểu dữ liệu, null count12df.describe() # Thống kê mô tả (numeric)13df.dtypes # Kiểu dữ liệu các cột14df.columns # Tên các cột15df.index # Index3.2 Unique và Value Counts
Python
1# Giá trị unique2df['city'].unique() # Array unique values3df['city'].nunique() # Số lượng unique45# Đếm tần suất6df['city'].value_counts()7# Hanoi 1008# HCMC 809# Danang 501011# Với tỷ lệ %12df['city'].value_counts(normalize=True)4. Selection - Chọn Dữ Liệu
4.1 Chọn cột
Python
1# Một cột → Series2df['name']3df.name45# Nhiều cột → DataFrame6df[['name', 'age']]78# Chọn cột bằng filter9df.filter(like='name') # Cột chứa 'name'10df.filter(regex='^col_') # Cột bắt đầu với 'col_'4.2 Chọn dòng với loc và iloc
Python
1# loc - by label (tên index/column)2df.loc[0] # Dòng có index 03df.loc[0:5] # Dòng 0 đến 5 (inclusive!)4df.loc[0, 'name'] # Ô [0, 'name']5df.loc[:, 'name':'age'] # Tất cả dòng, cột từ name đến age67# iloc - by position (số thứ tự)8df.iloc[0] # Dòng đầu tiên9df.iloc[0:5] # Dòng 0 đến 4 (exclusive!)10df.iloc[0, 0] # Ô [dòng 0, cột 0]11df.iloc[:, 0:2] # Tất cả dòng, 2 cột đầu4.3 Boolean Indexing (Lọc)
Python
1# Lọc với điều kiện2df[df['age'] > 30]34# Nhiều điều kiện5df[(df['age'] > 25) & (df['city'] == 'Hanoi')] # AND6df[(df['age'] > 30) | (df['city'] == 'HCMC')] # OR7df[~(df['age'] > 30)] # NOT89# isin10df[df['city'].isin(['Hanoi', 'HCMC'])]1112# between13df[df['age'].between(25, 35)]1415# String methods16df[df['name'].str.contains('A')]17df[df['name'].str.startswith('A')]4.4 Query Method
Python
1# Query - SQL-like syntax2df.query('age > 30')3df.query('age > 25 and city == "Hanoi"')4df.query('city in ["Hanoi", "HCMC"]')56# Với variables7min_age = 258df.query('age > @min_age')5. Transformations
5.1 Thêm/Sửa cột
Python
1# Thêm cột mới2df['country'] = 'Vietnam'3df['age_group'] = df['age'].apply(lambda x: 'Young' if x < 30 else 'Adult')45# Tính toán cột mới6df['total'] = df['price'] * df['quantity']78# assign - Thêm nhiều cột (trả về df mới)9df = df.assign(10 total = df['price'] * df['quantity'],11 tax = df['price'] * 0.112)5.2 Apply và Map
Python
1# apply - Áp dụng function2df['age_squared'] = df['age'].apply(lambda x: x ** 2)34# apply cho cả dòng5def calculate_score(row):6 return row['score1'] + row['score2'] * 0.578df['final_score'] = df.apply(calculate_score, axis=1)910# map - Mapping giá trị11city_code = {'Hanoi': 'HN', 'HCMC': 'HCM', 'Danang': 'DN'}12df['city_code'] = df['city'].map(city_code)1314# replace15df['status'] = df['status'].replace({'active': 1, 'inactive': 0})5.3 Sắp xếp
Python
1# Sort by column2df.sort_values('age')3df.sort_values('age', ascending=False) # Giảm dần45# Sort by multiple columns6df.sort_values(['city', 'age'], ascending=[True, False])78# Sort by index9df.sort_index()5.4 Rename
Python
1# Rename columns2df.rename(columns={'old_name': 'new_name'})34# Rename với function5df.rename(columns=str.upper) # UPPERCASE6df.rename(columns=str.lower) # lowercase7df.columns = df.columns.str.replace(' ', '_') # Replace spaces6. Groupby - Nhóm và Tổng hợp
6.1 Basic Groupby
Python
1# Groupby một cột2df.groupby('city')['revenue'].sum()3df.groupby('city')['revenue'].mean()45# Groupby nhiều cột6df.groupby(['city', 'category'])['revenue'].sum()78# Nhiều aggregations9df.groupby('city').agg({10 'revenue': 'sum',11 'quantity': 'mean',12 'customers': 'count'13})6.2 Aggregation Functions
Python
1# Các hàm aggregation2df.groupby('city').agg(3 total_revenue = ('revenue', 'sum'),4 avg_revenue = ('revenue', 'mean'),5 max_revenue = ('revenue', 'max'),6 order_count = ('order_id', 'count'),7 unique_products = ('product_id', 'nunique')8)910# Custom aggregation11df.groupby('city')['revenue'].agg(['sum', 'mean', 'std', 'count'])1213# Lambda in agg14df.groupby('city')['revenue'].agg(lambda x: x.max() - x.min())6.3 Transform và Filter
Python
1# transform - Giữ nguyên shape2df['city_mean'] = df.groupby('city')['revenue'].transform('mean')34# Tính % so với group5df['pct_of_group'] = df['revenue'] / df.groupby('city')['revenue'].transform('sum')67# filter - Lọc groups8df.groupby('city').filter(lambda x: x['revenue'].sum() > 10000)7. Merge và Join
7.1 Merge (như SQL JOIN)
Python
1# Sample DataFrames2orders = pd.DataFrame({3 'order_id': [1, 2, 3],4 'customer_id': [101, 102, 101],5 'amount': [100, 200, 150]6})78customers = pd.DataFrame({9 'customer_id': [101, 102, 103],10 'name': ['Alice', 'Bob', 'Charlie']11})1213# Inner join (default)14pd.merge(orders, customers, on='customer_id')1516# Left join17pd.merge(orders, customers, on='customer_id', how='left')1819# Right join20pd.merge(orders, customers, on='customer_id', how='right')2122# Outer join23pd.merge(orders, customers, on='customer_id', how='outer')2425# Join on different column names26pd.merge(orders, customers, left_on='cust_id', right_on='customer_id')7.2 Concat
Python
1# Concat dọc (thêm dòng)2df_all = pd.concat([df1, df2, df3])3df_all = pd.concat([df1, df2], ignore_index=True)45# Concat ngang (thêm cột)6df_wide = pd.concat([df1, df2], axis=1)8. Pivot và Melt
8.1 Pivot Table
Python
1# Tạo pivot table2pivot = df.pivot_table(3 values='revenue',4 index='city',5 columns='month',6 aggfunc='sum',7 fill_value=08)910# Nhiều aggregations11pivot = df.pivot_table(12 values='revenue',13 index='city',14 columns='month',15 aggfunc=['sum', 'mean', 'count']16)8.2 Melt (Unpivot)
Python
1# Wide to Long format2df_long = df.melt(3 id_vars=['name', 'city'],4 value_vars=['jan', 'feb', 'mar'],5 var_name='month',6 value_name='revenue'7)9. Export Dữ Liệu
Python
1# CSV2df.to_csv("output.csv", index=False)3df.to_csv("output.csv", index=False, encoding="utf-8-sig") # Excel friendly45# Excel6df.to_excel("output.xlsx", sheet_name="Data", index=False)78# JSON9df.to_json("output.json", orient="records")1011# Parquet (hiệu quả)12df.to_parquet("output.parquet")Tổng Kết
Trong bài này, bạn đã học:
- ✅ Tạo DataFrame từ nhiều nguồn
- ✅ Khám phá dữ liệu với head, info, describe
- ✅ Selection với loc, iloc và boolean indexing
- ✅ Transformations: apply, map, assign
- ✅ Groupby và aggregations
- ✅ Merge, Join, Concat
- ✅ Pivot table và Melt
Bài tiếp theo: Polars - Thư viện xử lý dữ liệu siêu nhanh!
