Pandas là thư viện phổ biến nhất cho data science/analytics trong Python. Cung cấp cấu trúc dữ liệu Series (1D) và DataFrame (2D) mạnh mẽ.
Cài đặt
pip install pandas matplotlib
Series - Mảng 1 chiều có nhãn
import pandas as pd
# Tạo Series
s = pd.Series([12, 24, 36, 48, 60, 72, 84])
print(s)
# Custom index
s = pd.Series([12, 24, 36, 48, 60, 72, 84],
index=['ind0','ind1','ind2','ind3','ind4','ind5','ind6'])
print(s)
# Truy xuất
print(s['ind3']) # 48
print(s[['ind0','ind3']]) # nhiều index
# Gán nhóm
s[['ind0','ind3','ind6']] = 36
# Lọc & toán học
print(s[s > 24])
print(s[s < 24] * 2)
# Như dict
s2 = pd.Series({'a':9, 'b':18, 'c':27, 'd':36})
s2.name = 'Numbers'
s2.index.name = 'letters'
print(s2)
DataFrame - Bảng dữ liệu 2 chiều
df = pd.DataFrame({
'Country': ['China', 'India', 'Indonesia', 'Pakistan'],
'Population': [1420062022, 1368737513, 269536482, 204596442],
'Area': [9388211, 2973190, 1811570, 770880]
}, index=['CHA', 'IND', 'IDO', 'PAK'])
print(df)
print(df.columns)
print(df.index)
print(df['Country']) # Series
print(df.loc['IND']) # Row bằng label
print(df.iloc[1]) # Row bằng vị trí
print(df.loc[['CHI','IND'], 'Population'])
Đọc/ghi file
# CSV
df = pd.read_csv('data.csv', sep=',')
df.to_csv('output.csv', index=False)
# Excel
df = pd.read_excel('data.xlsx')
df.to_excel('output.xlsx')
# JSON
df = pd.read_json('data.json')
df.to_json('output.json')
Aggregation & Grouping
# Titanic dataset example
titanic = pd.read_csv('titanic.csv')
# Số hành khách sống/sống theo giới tính
print(titanic.groupby(['Sex', 'Survived'])['PassengerID'].count())
# Theo lớp cabin
print(titanic.groupby(['PClass', 'Survived'])['PassengerID'].count())
Time Series Analysis
amzn = pd.read_csv('AMZN.csv', index_col='Date', parse_dates=True)
amzn = amzn.sort_index()
print(amzn.loc['2015-04', 'Close'].mean()) # Giá đóng cửa trung bình tháng 4/2015
Visualization với Matplotlib
import matplotlib.pyplot as plt
df = pd.read_csv('AMZN.csv', index_col='Date', parse_dates=True)
df = df.sort_index()
df.loc['2014-06':'2018-08', ['Close']].astype(float).plot()
plt.title('Amazon Stock Price')
plt.show()

Tóm tắt quy trình phân tích
- Load data (
read_csv,read_excel, ...) - Explore (
head(),info(),describe()) - Clean (missing values, dtype, outliers)
- Transform (groupby, pivot, resample time series)
- Analyze (stats, correlation, modeling)
- Visualize (plot, seaborn, plotly)
- Export/Report