Python Cho Data Science — Pandas, NumPy Và Matplotlib Cơ Bản
Khởi đầu với Data Science trong Python: làm quen với Pandas, NumPy, Matplotlib qua ví dụ thực tế.
Python là ngôn ngữ số 1 cho Data Science — đơn giản, hệ sinh thái khổng lồ. Bài này dẫn bạn từ 0 đến phân tích dữ liệu cơ bản.
Cài Đặt#
pip install pandas numpy matplotlib seaborn jupyter
# Hoặc dùng conda
conda create -n ds python=3.12 pandas numpy matplotlib seaborn jupyterbashNumPy — Nền Tảng Tính Toán Số#
NumPy là thư viện nền tảng — cung cấp array và các phép toán số học hiệu quả.
import numpy as np
# Tạo array
arr = np.array([1, 2, 3, 4, 5])
zeros = np.zeros((3, 4))
ones = np.ones((2, 3))
rng = np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
lin = np.linspace(0, 1, 5) # [0, 0.25, 0.5, 0.75, 1]
# Phép toán — vectorized, không cần loop
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(a + b) # [5, 7, 9]
print(a * b) # [4, 10, 18]
print(a.mean()) # 2.0
print(a.sum()) # 6
# Indexing & slicing
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(matrix[0, 1]) # 2
print(matrix[:, :2]) # [[1, 2], [4, 5], [7, 8]]
print(matrix[matrix > 5]) # [6, 7, 8, 9] — boolean indexingpythonPandas — Xương Sống Của Data Science#
Series vs DataFrame#
import pandas as pd
# Series — 1 cột
s = pd.Series([10, 20, 30, 40], index=['a', 'b', 'c', 'd'])
# DataFrame — bảng
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie'],
'age': [25, 30, 35],
'salary': [50000, 60000, 70000],
})pythonĐọc/Ghi Dữ Liệu#
# CSV
df = pd.read_csv('sales.csv')
df.to_csv('cleaned.csv', index=False)
# Excel
df = pd.read_excel('data.xlsx', sheet_name='Sheet1')
# JSON
df = pd.read_json('data.json')
# SQL
from sqlalchemy import create_engine
engine = create_engine('postgresql://user:pass@localhost/db')
df = pd.read_sql('SELECT * FROM users', engine)pythonKhám Phá Dữ Liệu#
df.head(10) # 10 dòng đầu
df.info() # Kiểu dữ liệu, null count
df.describe() # Thống kê cơ bản
df.shape # (số dòng, số cột)
df.columns # Danh sách cột
df['column'].value_counts() # Đếm giá trị
df.isnull().sum() # Số null mỗi cộtpythonLọc & Chọn#
# Lọc cột
df['name']
df[['name', 'salary']]
# Lọc dòng
df[df['age'] > 30]
df[(df['age'] > 25) & (df['salary'] > 55000)]
df.query('age > 25 and salary > 55000')
# Lọc bằng loc/iloc
df.loc[0:2, ['name', 'salary']] # Label-based
df.iloc[0:2, 0:2] # Index-basedpythonXử Lý Missing Data#
# Kiểm tra
df.isnull().sum()
# Xóa
df.dropna() # Xóa dòng có null
df.dropna(subset=['email']) # Xóa dòng null ở cột cụ thể
# Điền giá trị
df['age'].fillna(df['age'].median(), inplace=True)
df['category'].fillna('Unknown', inplace=True)
df.fillna(method='ffill') # Forward fillpythonGroup By & Aggregate#
# Doanh thu trung bình theo phòng ban
df.groupby('department')['salary'].mean()
# Nhiều aggregate
df.groupby('department').agg({
'salary': ['mean', 'median', 'min', 'max'],
'age': 'mean',
})
# Pivot table
pd.pivot_table(df, values='salary', index='department',
columns='gender', aggfunc='mean')pythonApply — Transform Dữ Liệu#
# Tạo cột mới
df['bonus'] = df['salary'] * 0.1
# Apply function
df['name_length'] = df['name'].apply(len)
# Map giá trị
df['gender_code'] = df['gender'].map({'Male': 0, 'Female': 1})
# Vectorized string operations
df['email_domain'] = df['email'].str.split('@').str[1]pythonMatplotlib & Seaborn — Trực Quan Hóa#
Matplotlib Cơ Bản#
import matplotlib.pyplot as plt
# Line plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y, marker='o', linestyle='--', color='blue')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.title('Simple Line Plot')
plt.show()
# Bar chart
categories = ['A', 'B', 'C', 'D']
values = [23, 45, 56, 78]
plt.bar(categories, values, color='green')
plt.show()
# Histogram
data = np.random.normal(170, 10, 1000)
plt.hist(data, bins=30, edgecolor='black')
plt.xlabel('Height (cm)')
plt.ylabel('Frequency')
plt.show()pythonSeaborn — Đẹp Hơn, Dễ Hơn#
import seaborn as sns
# Load dataset mẫu
tips = sns.load_dataset('tips')
# Scatter plot
sns.scatterplot(data=tips, x='total_bill', y='tip', hue='time')
# Box plot
sns.boxplot(data=tips, x='day', y='total_bill')
# Correlation heatmap
corr = tips.select_dtypes(include='number').corr()
sns.heatmap(corr, annot=True, cmap='coolwarm')
# Pair plot — quan hệ giữa nhiều biến
sns.pairplot(tips, hue='sex')pythonVí Dụ Hoàn Chỉnh — Phân Tích Sales#
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# 1. Đọc dữ liệu
df = pd.read_csv('sales.csv')
# 2. Làm sạch
df.dropna(subset=['revenue'], inplace=True)
df['date'] = pd.to_datetime(df['date'])
df['month'] = df['date'].dt.month
# 3. Phân tích
monthly_revenue = df.groupby('month')['revenue'].sum()
top_products = df.groupby('product')['revenue'].sum().sort_values(ascending=False).head(10)
# 4. Trực quan
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
axes[0].plot(monthly_revenue.index, monthly_revenue.values, marker='o')
axes[0].set_title('Monthly Revenue')
axes[0].set_xlabel('Month')
axes[0].set_ylabel('Revenue')
sns.barplot(x=top_products.values, y=top_products.index, ax=axes[1])
axes[1].set_title('Top 10 Products')
axes[1].set_xlabel('Revenue')
plt.tight_layout()
plt.show()pythonKết Luận#
Data Science trong Python gồm 3 thư viện cốt lõi:
- NumPy — Array và tính toán số
- Pandas — Thao tác dữ liệu dạng bảng
- Matplotlib/Seaborn — Trực quan hóa
Học theo thứ tự đó. Dành 80% thời gian cho Pandas — nó là thứ bạn dùng nhiều nhất. Jupyter Notebook là môi trường lý tưởng để thực hành.