Python 科學(xué)計(jì)算的五大庫(kù)
Python 是一門強(qiáng)大的編程語(yǔ)言,在科學(xué)計(jì)算領(lǐng)域有著廣泛的應(yīng)用。今天我們就來(lái)聊聊 Python 科學(xué)計(jì)算中常用的五大庫(kù):NumPy、Pandas、Matplotlib、SciPy 和 Scikit-learn。
1. NumPy
NumPy 是 Python 中用于處理數(shù)值數(shù)據(jù)的基礎(chǔ)庫(kù)。它提供了高效的數(shù)組對(duì)象和各種數(shù)學(xué)函數(shù),使得數(shù)值計(jì)算變得非常方便。
基本使用:
import numpy as np
# 創(chuàng)建一個(gè)一維數(shù)組
arr = np.array([1, 2, 3, 4, 5])
print(arr) # 輸出: [1 2 3 4 5]
# 創(chuàng)建一個(gè)多維數(shù)組
multi_dim_arr = np.array([[1, 2, 3], [4, 5, 6]])
print(multi_dim_arr)
# 輸出:
# [[1 2 3]
# [4 5 6]]
# 數(shù)組的基本操作
print(arr + 1) # 輸出: [2 3 4 5 6]
print(arr * 2) # 輸出: [2 4 6 8 10]
高級(jí)用法:
# 生成隨機(jī)數(shù)組
random_arr = np.random.rand(3, 3)
print(random_arr)
# 數(shù)組切片
sliced_arr = arr[1:4]
print(sliced_arr) # 輸出: [2 3 4]
# 廣播機(jī)制
arr2 = np.array([1, 2, 3])
result = arr + arr2
print(result) # 輸出: [2 4 6 6 7]
2. Pandas
Pandas 是一個(gè)強(qiáng)大的數(shù)據(jù)處理和分析庫(kù),特別適合處理表格數(shù)據(jù)。
基本使用:
import pandas as pd
# 創(chuàng)建一個(gè) 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
高級(jí)用法:
# 讀取 CSV 文件
df = pd.read_csv('data.csv')
print(df.head()) # 顯示前 5 行
# 數(shù)據(jù)篩選
filtered_df = df[df['Age'] > 30]
print(filtered_df)
# 數(shù)據(jù)聚合
grouped_df = df.groupby('Name').mean()
print(grouped_df)
3. Matplotlib
Matplotlib 是一個(gè)用于繪制圖表的庫(kù),可以生成各種靜態(tài)、動(dòng)態(tài)和交互式圖表。
基本使用:
import matplotlib.pyplot as plt
# 繪制簡(jiǎn)單的折線圖
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()
高級(jí)用法:
# 繪制多個(gè)子圖
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') # 藍(lán)色散點(diǎn)圖
ax2.set_title('Subplot 2')
plt.show()
4. SciPy
SciPy 是一個(gè)用于科學(xué)和工程計(jì)算的庫(kù),提供了許多高級(jí)數(shù)學(xué)函數(shù)和算法。
基本使用:
from scipy import stats
# 計(jì)算均值和標(biāo)準(zhǔn)差
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
高級(jí)用法:
# 最小二乘擬合
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 是一個(gè)用于機(jī)器學(xué)習(xí)的庫(kù),提供了大量的算法和工具。
基本使用:
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
# 加載 Iris 數(shù)據(jù)集
iris = load_iris()
X = iris.data
y = iris.target
# 劃分訓(xùn)練集和測(cè)試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 訓(xùn)練模型
model = LogisticRegression()
model.fit(X_train, y_train)
# 預(yù)測(cè)
predictions = model.predict(X_test)
print(predictions)
高級(jí)用法:
# 交叉驗(yàn)證
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)}')
實(shí)戰(zhàn)案例:股票價(jià)格預(yù)測(cè)
假設(shè)我們要預(yù)測(cè)某只股票的未來(lái)價(jià)格。我們可以使用 Pandas 處理數(shù)據(jù),NumPy 進(jìn)行數(shù)值計(jì)算,Scikit-learn 構(gòu)建預(yù)測(cè)模型。
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
# 讀取股票數(shù)據(jù)
df = pd.read_csv('stock_prices.csv')
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)
# 選擇特征和目標(biāo)變量
X = df[['Open', 'High', 'Low', 'Volume']].values
y = df['Close'].values
# 劃分訓(xùn)練集和測(cè)試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 訓(xùn)練模型
model = LinearRegression()
model.fit(X_train, y_train)
# 預(yù)測(cè)
predictions = model.predict(X_test)
# 可視化結(jié)果
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()
總結(jié)
本文介紹了 Python 科學(xué)計(jì)算中常用的五大庫(kù):NumPy、Pandas、Matplotlib、SciPy 和 Scikit-learn。我們從基本使用到高級(jí)用法,逐步展示了每個(gè)庫(kù)的核心功能和應(yīng)用場(chǎng)景。通過(guò)實(shí)戰(zhàn)案例,我們進(jìn)一步鞏固了這些庫(kù)的綜合應(yīng)用。