Tutorial

Top 5 thư viện Python cho Data Science

Những thư viện Python quan trọng nhất mà tôi sử dụng hàng ngày

5/1/2024
20 phút
Python
Data Science
Libraries

Top 5 thư viện Python cho Data Science mà tôi dùng mỗi ngày

Sau hơn 3 năm làm việc trong lĩnh vực Data Science, tôi đã sử dụng rất nhiều thư viện Python khác nhau. Trong bài viết này, tôi sẽ chia sẻ top 5 thư viện mà tôi sử dụng hàng ngày và tại sao chúng lại quan trọng đến vậy.

1. Pandas - Vua của Data Manipulation

Pandas là thư viện không thể thiếu cho bất kỳ Data Scientist nào. Nó cung cấp các cấu trúc dữ liệu mạnh mẽ và linh hoạt để làm việc với dữ liệu có cấu trúc.

Tại sao Pandas quan trọng?

import pandas as pd
import numpy as np

# Đọc dữ liệu từ CSV
df = pd.read_csv('sales_data.csv')

# Xem thông tin cơ bản
print(df.info())
print(df.describe())

# Lọc dữ liệu
high_sales = df[df['sales'] > 1000]

# Nhóm và tổng hợp
monthly_sales = df.groupby('month')['sales'].sum()

# Xử lý missing values
df_clean = df.dropna()
df_filled = df.fillna(df.mean())

Các tính năng yêu thích của tôi:

  • DataFrame và Series: Cấu trúc dữ liệu trực quan và dễ sử dụng
  • Groupby operations: Tổng hợp dữ liệu cực kỳ mạnh mẽ
  • Pivot tables: Tạo bảng tổng hợp như Excel
  • Time series handling: Xử lý dữ liệu thời gian chuyên nghiệp

2. NumPy - Nền tảng của Scientific Computing

NumPy là thư viện cơ bản nhất cho scientific computing trong Python. Hầu hết các thư viện khác đều được xây dựng trên nền tảng NumPy.

Tại sao NumPy quan trọng?

import numpy as np

# Tạo arrays
arr = np.array([1, 2, 3, 4, 5])
matrix = np.random.randn(1000, 1000)

# Vectorized operations (nhanh hơn loops rất nhiều)
result = np.sqrt(arr**2 + 1)

# Broadcasting
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([1, 2, 3])
result = a + b  # Broadcasting magic!

# Statistical functions
mean_val = np.mean(matrix)
std_val = np.std(matrix)

Điểm mạnh của NumPy:

  • Performance: C được viết bằng C, nhanh hơn Python thuần
  • Memory efficiency: Sử dụng bộ nhớ hiệu quả
  • Broadcasting: Thực hiện operations trên arrays có shape khác nhau
  • Mathematical functions: Đầy đủ các hàm toán học

3. Scikit-learn - Machine Learning Made Easy

Scikit-learn là thư viện machine learning phổ biến nhất trong Python. Nó cung cấp các thuật toán ML đơn giản và hiệu quả.

Tại sao Scikit-learn quan trọng?

from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report
from sklearn.preprocessing import StandardScaler

# Chuẩn bị dữ liệu
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# Chuẩn hóa dữ liệu
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# Training model
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train_scaled, y_train)

# Đánh giá
y_pred = model.predict(X_test_scaled)
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.2f}")

Các tính năng yêu thích:

  • Consistent API: Tất cả models đều có cùng interface
  • Pipeline: Kết hợp nhiều bước preprocessing và modeling
  • Cross-validation: Đánh giá model một cách robust
  • Feature selection: Chọn features quan trọng nhất

4. Matplotlib & Seaborn - Visualization Powerhouse

MatplotlibSeaborn là bộ đôi visualization không thể thiếu cho Data Science.

Tại sao visualization quan trọng?

import matplotlib.pyplot as plt
import seaborn as sns

# Thiết lập style
plt.style.use('seaborn-v0_8')
sns.set_palette("husl")

# Scatter plot
plt.figure(figsize=(10, 6))
plt.scatter(df['age'], df['income'], alpha=0.6)
plt.xlabel('Age')
plt.ylabel('Income')
plt.title('Age vs Income Relationship')
plt.show()

# Heatmap correlation
plt.figure(figsize=(12, 8))
correlation_matrix = df.corr()
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', center=0)
plt.title('Feature Correlation Matrix')
plt.show()

# Distribution plots
fig, axes = plt.subplots(2, 2, figsize=(15, 10))
sns.histplot(df['sales'], ax=axes[0,0])
sns.boxplot(df['category'], df['sales'], ax=axes[0,1])
sns.violinplot(df['region'], df['sales'], ax=axes[1,0])
sns.scatterplot(df['marketing'], df['sales'], hue=df['category'], ax=axes[1,1])
plt.tight_layout()
plt.show()

Lý do yêu thích:

  • Matplotlib: Flexible và customizable
  • Seaborn: Statistical plots đẹp và dễ sử dụng
  • Integration: Hoạt động tốt với Pandas DataFrames
  • Publication ready: Có thể xuất ra các format chất lượng cao

5. Requests - Web Scraping và API Integration

Requests là thư viện để thực hiện HTTP requests một cách đơn giản và elegant.

Tại sao Requests quan trọng?

import requests
import json
from datetime import datetime

# API calls
def fetch_weather_data(city):
    api_key = "your_api_key"
    url = f"http://api.openweathermap.org/data/2.5/weather"
    params = {
        'q': city,
        'appid': api_key,
        'units': 'metric'
    }

    response = requests.get(url, params=params)

    if response.status_code == 200:
        data = response.json()
        return {
            'temperature': data['main']['temp'],
            'humidity': data['main']['humidity'],
            'description': data['weather'][0]['description']
        }
    else:
        return None

# Web scraping
def scrape_news_headlines():
    url = "https://news.ycombinator.com"
    response = requests.get(url)

    if response.status_code == 200:
        # Sử dụng BeautifulSoup để parse HTML
        from bs4 import BeautifulSoup
        soup = BeautifulSoup(response.content, 'html.parser')
        headlines = soup.find_all('a', class_='storylink')
        return [headline.text for headline in headlines[:10]]

    return []

# Data collection
news_data = scrape_news_headlines()
weather_data = fetch_weather_data('Ho Chi Minh City')

Use cases thực tế:

  • API integration: Kết nối với các dịch vụ bên ngoài
  • Web scraping: Thu thập dữ liệu từ websites
  • Data pipeline: Tự động hóa việc thu thập dữ liệu
  • Real-time data: Lấy dữ liệu real-time cho analysis

Bonus: Thư viện khác đáng chú ý

Jupyter Notebook

# Magic commands trong Jupyter
%matplotlib inline
%load_ext autoreload
%autoreload 2

# Timing code execution
%timeit some_function()

Plotly (Interactive Visualization)

import plotly.express as px
import plotly.graph_objects as go

# Interactive scatter plot
fig = px.scatter(df, x='age', y='income', color='category',
                 size='sales', hover_data=['name'])
fig.show()

Kết luận

5 thư viện này là nền tảng vững chắc cho bất kỳ Data Scientist nào. Chúng không chỉ mạnh mẽ mà còn có community support tuyệt vời và documentation chi tiết.

Lời khuyên của tôi:

  1. Master Pandas trước: Đây là thư viện quan trọng nhất
  2. Hiểu NumPy: Nền tảng của mọi thứ
  3. Practice với Scikit-learn: Bắt đầu với các thuật toán đơn giản
  4. Visualize everything: Dữ liệu không có visualization là dữ liệu chết
  5. Automate data collection: Sử dụng Requests để tự động hóa

Bạn có thư viện Python nào khác mà bạn sử dụng hàng ngày không? Hãy chia sẻ trong comment nhé!

My photo

Tân Đoàn

AI Automation • Python Dev

Trực tuyến
Portfolio Website
Hồ Chí Minh, VN
Tân Đoàn
Data Scientist với niềm đam mê chia sẻ kiến thức về AI, Machine Learning và Python.
Tìm hiểu thêm