偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

Python 科學(xué)計算的五大庫

開發(fā)
本文介紹了 Python 科學(xué)計算中常用的五大庫:NumPy、Pandas、Matplotlib、SciPy 和 Scikit-learn。

Python 是一門強大的編程語言,在科學(xué)計算領(lǐng)域有著廣泛的應(yīng)用。今天我們就來聊聊 Python 科學(xué)計算中常用的五大庫:NumPy、Pandas、Matplotlib、SciPy 和 Scikit-learn。

1. NumPy

NumPy 是 Python 中用于處理數(shù)值數(shù)據(jù)的基礎(chǔ)庫。它提供了高效的數(shù)組對象和各種數(shù)學(xué)函數(shù),使得數(shù)值計算變得非常方便。

基本使用:

import numpy as np

# 創(chuàng)建一個一維數(shù)組
arr = np.array([1, 2, 3, 4, 5])
print(arr)  # 輸出: [1 2 3 4 5]

# 創(chuàng)建一個多維數(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]

高級用法:

# 生成隨機數(shù)組
random_arr = np.random.rand(3, 3)
print(random_arr)

# 數(shù)組切片
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 是一個強大的數(shù)據(jù)處理和分析庫,特別適合處理表格數(shù)據(jù)。

基本使用:

import pandas as pd

# 創(chuàng)建一個 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 行

# 數(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 是一個用于繪制圖表的庫,可以生成各種靜態(tài)、動態(tài)和交互式圖表。

基本使用:

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 是一個用于科學(xué)和工程計算的庫,提供了許多高級數(shù)學(xué)函數(shù)和算法。

基本使用:

from scipy import stats

# 計算均值和標(biāo)準差
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 是一個用于機器學(xué)習(xí)的庫,提供了大量的算法和工具。

基本使用:

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)練集和測試集
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ù)測
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)}')

實戰(zhàn)案例:股票價格預(yù)測

假設(shè)我們要預(yù)測某只股票的未來價格。我們可以使用 Pandas 處理數(shù)據(jù),NumPy 進行數(shù)值計算,Scikit-learn 構(gòu)建預(yù)測模型。

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)練集和測試集
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ù)測
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é)計算中常用的五大庫:NumPy、Pandas、Matplotlib、SciPy 和 Scikit-learn。我們從基本使用到高級用法,逐步展示了每個庫的核心功能和應(yīng)用場景。通過實戰(zhàn)案例,我們進一步鞏固了這些庫的綜合應(yīng)用。

責(zé)任編輯:趙寧寧 來源: 小白PythonAI編程
相關(guān)推薦

2021-01-13 15:13:07

Python開發(fā) 工具

2019-01-08 16:25:42

數(shù)據(jù)科學(xué)機器學(xué)習(xí)神經(jīng)網(wǎng)絡(luò)

2011-04-21 11:39:13

2019-06-04 10:40:07

2022-01-18 06:53:10

量子科學(xué)量子安全量子計算

2023-10-30 15:16:59

Python庫Python開發(fā)

2013-08-05 10:01:09

云計算

2016-08-04 16:36:39

云計算

2019-10-12 10:09:41

云計算數(shù)據(jù)物聯(lián)網(wǎng)

2018-07-11 06:52:47

云計算云遷移

2014-12-04 11:36:02

云計算云計算技術(shù)特點

2012-05-07 15:00:37

政府云計算應(yīng)用

2023-09-08 10:12:48

云計算云遷移

2015-03-16 11:01:52

云計算誤解云計算公有云

2023-11-28 11:22:51

Pythonitertools庫工具

2011-02-17 11:18:29

PythonWebRuby

2015-02-09 09:21:21

2012-06-14 08:54:40

DaaS桌面即服務(wù)云計算

2022-10-31 11:00:51

物聯(lián)網(wǎng)邊緣計算

2010-03-16 16:35:06

云計算
點贊
收藏

51CTO技術(shù)棧公眾號