Python 科學計算的五大庫
Python 是一門強大的編程語言,在科學計算領域有著廣泛的應用。今天我們就來聊聊 Python 科學計算中常用的五大庫:NumPy、Pandas、Matplotlib、SciPy 和 Scikit-learn。
1. NumPy
NumPy 是 Python 中用于處理數值數據的基礎庫。它提供了高效的數組對象和各種數學函數,使得數值計算變得非常方便。
基本使用:
import numpy as np
# 創建一個一維數組
arr = np.array([1, 2, 3, 4, 5])
print(arr) # 輸出: [1 2 3 4 5]
# 創建一個多維數組
multi_dim_arr = np.array([[1, 2, 3], [4, 5, 6]])
print(multi_dim_arr)
# 輸出:
# [[1 2 3]
# [4 5 6]]
# 數組的基本操作
print(arr + 1) # 輸出: [2 3 4 5 6]
print(arr * 2) # 輸出: [2 4 6 8 10]
高級用法:
# 生成隨機數組
random_arr = np.random.rand(3, 3)
print(random_arr)
# 數組切片
sliced_arr = arr[1:4]
print(sliced_arr) # 輸出: [2 3 4]
# 廣播機制
arr2 = np.array([1, 2, 3])
result = arr + arr2
print(result) # 輸出: [2 4 6 6 7]
2. Pandas
Pandas 是一個強大的數據處理和分析庫,特別適合處理表格數據。
基本使用:
import pandas as pd
# 創建一個 DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
df = pd.DataFrame(data)
print(df)
# 輸出:
# Name Age
# 0 Alice 25
# 1 Bob 30
# 2 Charlie 35
# 選擇列
ages = df['Age']
print(ages)
# 輸出:
# 0 25
# 1 30
# 2 35
# Name: Age, dtype: int64
高級用法:
# 讀取 CSV 文件
df = pd.read_csv('data.csv')
print(df.head()) # 顯示前 5 行
# 數據篩選
filtered_df = df[df['Age'] > 30]
print(filtered_df)
# 數據聚合
grouped_df = df.groupby('Name').mean()
print(grouped_df)
3. Matplotlib
Matplotlib 是一個用于繪制圖表的庫,可以生成各種靜態、動態和交互式圖表。
基本使用:
import matplotlib.pyplot as plt
# 繪制簡單的折線圖
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Line Plot')
plt.show()
高級用法:
# 繪制多個子圖
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))
ax1.plot(x, y, 'r') # 紅色折線
ax1.set_title('Subplot 1')
ax2.scatter(x, y, color='b') # 藍色散點圖
ax2.set_title('Subplot 2')
plt.show()
4. SciPy
SciPy 是一個用于科學和工程計算的庫,提供了許多高級數學函數和算法。
基本使用:
from scipy import stats
# 計算均值和標準差
data = [1, 2, 3, 4, 5]
mean = np.mean(data)
std_dev = np.std(data)
print(f'Mean: {mean}, Standard Deviation: {std_dev}')
# 輸出: Mean: 3.0, Standard Deviation: 1.4142135623730951
# 概率分布
dist = stats.norm(loc=0, scale=1)
print(dist.pdf(0)) # 輸出: 0.3989422804014327
高級用法:
# 最小二乘擬合
x = np.linspace(0, 10, 100)
y = 3 * x + 5 + np.random.normal(0, 1, 100)
slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
print(f'Slope: {slope}, Intercept: {intercept}')
# 輸出: Slope: 2.995805608425055, Intercept: 5.046887465309874
5. Scikit-learn
Scikit-learn 是一個用于機器學習的庫,提供了大量的算法和工具。
基本使用:
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
# 加載 Iris 數據集
iris = load_iris()
X = iris.data
y = iris.target
# 劃分訓練集和測試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 訓練模型
model = LogisticRegression()
model.fit(X_train, y_train)
# 預測
predictions = model.predict(X_test)
print(predictions)
高級用法:
# 交叉驗證
from sklearn.model_selection import cross_val_score
scores = cross_val_score(model, X, y, cv=5)
print(f'Cross-validation scores: {scores}')
print(f'Mean score: {np.mean(scores)}')
實戰案例:股票價格預測
假設我們要預測某只股票的未來價格。我們可以使用 Pandas 處理數據,NumPy 進行數值計算,Scikit-learn 構建預測模型。
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
# 讀取股票數據
df = pd.read_csv('stock_prices.csv')
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)
# 選擇特征和目標變量
X = df[['Open', 'High', 'Low', 'Volume']].values
y = df['Close'].values
# 劃分訓練集和測試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 訓練模型
model = LinearRegression()
model.fit(X_train, y_train)
# 預測
predictions = model.predict(X_test)
# 可視化結果
plt.figure(figsize=(10, 5))
plt.plot(y_test, label='Actual Prices')
plt.plot(predictions, label='Predicted Prices')
plt.xlabel('Time')
plt.ylabel('Price')
plt.title('Stock Price Prediction')
plt.legend()
plt.show()
總結
本文介紹了 Python 科學計算中常用的五大庫:NumPy、Pandas、Matplotlib、SciPy 和 Scikit-learn。我們從基本使用到高級用法,逐步展示了每個庫的核心功能和應用場景。通過實戰案例,我們進一步鞏固了這些庫的綜合應用。