Python與數(shù)據(jù)科學(xué)工具鏈之NumPy、Pandas、Matplotlib快速上手教程
“工欲善其事,必先利其器。”
——在機(jī)器學(xué)習(xí)的世界里,你的“器”就是 Python 數(shù)據(jù)科學(xué)工具鏈。
一、為什么工具鏈如此重要?
想象你要做一道菜。即使你背熟了所有食譜,如果廚房里只有生銹的刀、沒校準(zhǔn)的秤、漏底的鍋,你依然做不出好菜。
機(jī)器學(xué)習(xí)也是如此。
算法是“菜譜”,而 NumPy、Pandas、Matplotlib 就是你的“刀、秤、鍋”——它們構(gòu)成了現(xiàn)代數(shù)據(jù)科學(xué)工作的基礎(chǔ)設(shè)施。
很多初學(xué)者一上來就急著學(xué)“神經(jīng)網(wǎng)絡(luò)”“梯度提升”,卻連如何讀取一個(gè) CSV 文件都磕磕絆絆。結(jié)果是:想法很豐滿,代碼跑不動(dòng)。
本篇文章的目標(biāo)很明確:
? 讓你在 2 小時(shí)內(nèi)掌握三大核心庫的基礎(chǔ)用法;
? 能獨(dú)立完成 數(shù)據(jù)加載 → 清洗 → 探索 → 可視化 的完整流程;
? 為后續(xù)所有機(jī)器學(xué)習(xí)項(xiàng)目打下堅(jiān)實(shí)工具基礎(chǔ)。
不需要你成為專家,但要讓你不再被工具卡住。
二、環(huán)境準(zhǔn)備:5 分鐘搭建你的“數(shù)據(jù)廚房”
推薦方式:使用 Anaconda(最省心)
- 訪問 https://www.anaconda.com/products/distribution
- 下載對應(yīng)你操作系統(tǒng)的安裝包(Windows / macOS / Linux)
- 安裝時(shí)勾選 “Add to PATH”(Windows 用戶注意)
- 安裝完成后,打開 Anaconda Prompt(Windows)或終端(macOS/Linux)
?? Anaconda 自帶 Python、NumPy、Pandas、Matplotlib、Jupyter 等幾乎所有你需要的庫,避免依賴沖突。
驗(yàn)證安裝
在終端中輸入:
python --version
應(yīng)顯示 Python 3.9+。
然后啟動(dòng) Jupyter Notebook(推薦交互式開發(fā)環(huán)境):
jupyter notebook
瀏覽器會(huì)自動(dòng)打開一個(gè)文件管理界面——這就是你的“數(shù)據(jù)實(shí)驗(yàn)室”。
?? 替代方案:如果你已用
pip管理 Python,可手動(dòng)安裝:pip install numpy pandas matplotlib jupyter
三、NumPy:高效數(shù)值計(jì)算的基石
為什么需要 NumPy?
Python 原生的 list 雖然靈活,但在科學(xué)計(jì)算中存在兩大問題:
- 速度慢:每個(gè)元素都是 Python 對象,內(nèi)存開銷大;
- 不支持向量化運(yùn)算:無法直接對整個(gè)數(shù)組做加減乘除。
而 NumPy(Numerical Python) 提供了:
- ndarray:高效的多維數(shù)組對象;
- 廣播機(jī)制(Broadcasting):自動(dòng)對不同形狀的數(shù)組進(jìn)行運(yùn)算;
- C 語言底層實(shí)現(xiàn):比純 Python 快 10–100 倍。
?? 記?。簬缀跛袛?shù)據(jù)科學(xué)庫(Pandas、scikit-learn、TensorFlow)都基于 NumPy 構(gòu)建。
1. 創(chuàng)建數(shù)組
import numpy as np # 從列表創(chuàng)建 arr = np.array([1, 2, 3, 4]) print(arr) # [1 2 3 4] # 創(chuàng)建全零/全一數(shù)組 zeros = np.zeros(5) # [0. 0. 0. 0. 0.] ones = np.ones((2, 3)) # 2x3 全1矩陣 # 創(chuàng)建等差數(shù)列 linspace = np.linspace(0, 10, 5) # [0. 2.5 5. 7.5 10.] # 創(chuàng)建隨機(jī)數(shù)組 rand = np.random.rand(3, 2) # 3x2,值在[0,1)之間
2. 數(shù)組屬性與形狀操作
arr = np.array([[1, 2, 3], [4, 5, 6]])
print("形狀:", arr.shape) # (2, 3)
print("維度:", arr.ndim) # 2
print("元素總數(shù):", arr.size) # 6
print("數(shù)據(jù)類型:", arr.dtype) # int64
# 改變形狀(不改變數(shù)據(jù))
reshaped = arr.reshape(3, 2)
print(reshaped)
# [[1 2]
# [3 4]
# [5 6]]
# 展平為一維
flat = arr.flatten() # [1 2 3 4 5 6]
3. 向量化運(yùn)算(無需 for 循環(huán)?。?/h3>
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
# 元素級(jí)加法
print(a + b) # [5 7 9]
# 元素級(jí)乘法
print(a * b) # [4 10 18]
# 平方
print(a ** 2) # [1 4 9]
# 三角函數(shù)
print(np.sin(a)) # [0.8415 0.9093 0.1411]
# 條件篩選
print(a[a > 1]) # [2 3]
? 關(guān)鍵優(yōu)勢:這些操作在 C 層面并行執(zhí)行,速度極快。
a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) # 元素級(jí)加法 print(a + b) # [5 7 9] # 元素級(jí)乘法 print(a * b) # [4 10 18] # 平方 print(a ** 2) # [1 4 9] # 三角函數(shù) print(np.sin(a)) # [0.8415 0.9093 0.1411] # 條件篩選 print(a[a > 1]) # [2 3]
? 關(guān)鍵優(yōu)勢:這些操作在 C 層面并行執(zhí)行,速度極快。
4. 常用數(shù)學(xué)函數(shù)
arr = np.array([1, 2, 3, 4, 5])
print("均值:", np.mean(arr)) # 3.0
print("標(biāo)準(zhǔn)差:", np.std(arr)) # 1.414...
print("最大值:", np.max(arr)) # 5
print("索引最大值:", np.argmax(arr)) # 4
print("求和:", np.sum(arr)) # 15
?? 這些函數(shù)將貫穿你未來的模型評估、特征工程等環(huán)節(jié)。
四、Pandas:讓數(shù)據(jù)處理像 Excel 一樣直觀
如果說 NumPy 是“引擎”,那么 Pandas 就是“駕駛艙”——它提供了更貼近人類思維的數(shù)據(jù)結(jié)構(gòu)。
核心數(shù)據(jù)結(jié)構(gòu)
| 結(jié)構(gòu) | 維度 | 類比 |
|---|---|---|
Series | 1D | 帶標(biāo)簽的一列數(shù)據(jù)(如 Excel 的一列) |
DataFrame | 2D | 表格(如 Excel 工作表) |
1. 創(chuàng)建 DataFrame
import pandas as pd
# 從字典創(chuàng)建
data = {
'name': ['Alice', 'Bob', 'Charlie'],
'age': [25, 30, 35],
'city': ['NYC', 'LA', 'Chicago']
}
df = pd.DataFrame(data)
print(df)
輸出:
name age city 0 Alice 25 NYC 1 Bob 30 LA 2 Charlie 35 Chicago
2. 讀取真實(shí)數(shù)據(jù)(CSV/Excel)
我們將使用經(jīng)典的 泰坦尼克號(hào)乘客數(shù)據(jù)集(titanic.csv),可從 Kaggle 下載,或使用 seaborn 內(nèi)置版本:
# 方法1:從 seaborn 加載(推薦初學(xué)者)
import seaborn as sns
titanic = sns.load_dataset('titanic')
# 方法2:從本地 CSV 讀取
# titanic = pd.read_csv('titanic.csv')
print("前5行:")
print(titanic.head())
print("\n基本信息:")
print(titanic.info())
典型輸出:
<class 'pandas.core.frame.DataFrame'> RangeIndex: 891 entries, 0 to 890 Data columns (total 15 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 survived 891 non-null int64 1 pclass 891 non-null int64 2 sex 891 non-null object 3 age 714 non-null float64 4 sibsp 891 non-null int64 5 parch 891 non-null int64 6 fare 891 non-null float64 7 embarked 889 non-null object ...
?? 注意:
age和embarked有缺失值(Non-Null Count < 891)——這是真實(shí)數(shù)據(jù)的常態(tài)!
3. 基礎(chǔ)探索:了解你的數(shù)據(jù)
# 查看維度
print("形狀:", titanic.shape) # (891, 15)
# 統(tǒng)計(jì)摘要(僅數(shù)值列)
print(titanic.describe())
# 查看分類變量分布
print(titanic['sex'].value_counts())
# male 577
# female 314
# 檢查缺失值
print(titanic.isnull().sum())
# age 177
# embarked 2
# deck 688 ← 大量缺失,可能需刪除
4. 數(shù)據(jù)篩選與索引
# 單列(返回 Series) ages = titanic['age'] # 多列(返回 DataFrame) subset = titanic[['name', 'age', 'fare']] # 條件篩選 survived_females = titanic[(titanic['survived'] == 1) & (titanic['sex'] == 'female')] # 使用 .loc(基于標(biāo)簽) first_row = titanic.loc[0, ['name', 'age']] # 使用 .iloc(基于位置) first_three = titanic.iloc[:3, :5] # 前3行,前5列
?? 注意:
&代替and,|代替or,且條件要用括號(hào)包圍。
5. 處理缺失值(數(shù)據(jù)清洗第一步)
# 方案1:刪除含缺失的行(謹(jǐn)慎使用?。? titanic_clean1 = titanic.dropna() # 方案2:用均值填充年齡 titanic['age'].fillna(titanic['age'].mean(), inplace=True) # 方案3:用眾數(shù)填充登船港口 mode_embarked = titanic['embarked'].mode()[0] titanic['embarked'].fillna(mode_embarked, inplace=True) # 驗(yàn)證 print(titanic[['age', 'embarked']].isnull().sum()) # 應(yīng)為 0
? 最佳實(shí)踐:記錄你做了什么處理,因?yàn)檫@直接影響模型效果。
6. 特征工程初探(為 ML 做準(zhǔn)備)
# 創(chuàng)建新特征:家庭規(guī)模 = 兄弟姐妹 + 父母子女 + 自己
titanic['family_size'] = titanic['sibsp'] + titanic['parch'] + 1
# 分箱:將年齡分為兒童/成人/老人
titanic['age_group'] = pd.cut(
titanic['age'],
bins=[0, 18, 65, 100],
labels=['Child', 'Adult', 'Senior']
)
# 編碼分類變量(字符串 → 數(shù)字)
titanic['sex_encoded'] = titanic['sex'].map({'male': 0, 'female': 1})
# 查看結(jié)果
print(titanic[['age', 'age_group', 'sex', 'sex_encoded']].head())
?? 這些操作正是后續(xù)機(jī)器學(xué)習(xí)中“特征工程”的核心內(nèi)容。
五、Matplotlib 與 Seaborn:用圖表講好數(shù)據(jù)故事
“一圖勝千言”——在數(shù)據(jù)科學(xué)中,可視化是理解、溝通、發(fā)現(xiàn)的關(guān)鍵。
1. Matplotlib:基礎(chǔ)繪圖庫
import matplotlib.pyplot as plt
# 設(shè)置中文字體(避免亂碼)
plt.rcParams['font.sans-serif'] = ['SimHei'] # Windows
# plt.rcParams['font.family'] = 'Arial Unicode MS' # macOS
# 示例1:直方圖(年齡分布)
plt.figure(figsize=(8, 5))
plt.hist(titanic['age'], bins=20, color='skyblue', edgecolor='black')
plt.title('泰坦尼克號(hào)乘客年齡分布')
plt.xlabel('年齡')
plt.ylabel('人數(shù)')
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()
2. Seaborn:統(tǒng)計(jì)可視化利器(基于 Matplotlib)
Seaborn 提供更高層次的接口,一行代碼即可生成精美圖表。
import seaborn as sns
# 示例2:生存率 vs 性別(柱狀圖)
plt.figure(figsize=(6, 4))
sns.barplot(x='sex', y='survived', data=titanic)
plt.title('不同性別的生存率')
plt.ylabel('生存概率')
plt.show()
輸出將清晰顯示:女性生存率遠(yuǎn)高于男性(約 74% vs 19%)。
3. 散點(diǎn)圖:探索變量關(guān)系
# 年齡 vs 票價(jià),顏色表示是否生存
plt.figure(figsize=(8, 6))
sns.scatterplot(
x='age', y='fare',
hue='survived',
data=titanic,
alpha=0.7
)
plt.title('年齡與票價(jià)的關(guān)系(按生存狀態(tài)著色)')
plt.show()
4. 熱力圖:查看相關(guān)性
# 選擇數(shù)值列
numeric_cols = titanic.select_dtypes(include=['number']).columns
corr_matrix = titanic[numeric_cols].corr()
# 繪制熱力圖
plt.figure(figsize=(10, 8))
sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', center=0)
plt.title('數(shù)值特征相關(guān)性熱力圖')
plt.show()
?? 你會(huì)發(fā)現(xiàn)
pclass(艙位等級(jí))與fare(票價(jià))高度負(fù)相關(guān)(-0.55)——頭等艙票價(jià)高,等級(jí)數(shù)字?。?=頭等)。
六、端到端實(shí)戰(zhàn):從原始數(shù)據(jù)到洞察
現(xiàn)在,我們將整合三大工具,完成一個(gè)微型分析項(xiàng)目。
目標(biāo):分析泰坦尼克號(hào)乘客的生存影響因素
步驟1:加載與清洗
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# 加載數(shù)據(jù)
df = sns.load_dataset('titanic')
# 基礎(chǔ)清洗
df['age'].fillna(df['age'].median(), inplace=True)
df.drop(columns=['deck', 'embark_town'], inplace=True) # 刪除高缺失列
df.dropna(subset=['embarked'], inplace=True)
步驟2:創(chuàng)建新特征
df['family_size'] = df['sibsp'] + df['parch'] + 1 df['is_alone'] = (df['family_size'] == 1).astype(int)
步驟3:可視化關(guān)鍵發(fā)現(xiàn)
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# 1. 艙位等級(jí) vs 生存率
sns.barplot(x='pclass', y='survived', data=df, ax=axes[0,0])
axes[0,0].set_title('艙位等級(jí)與生存率')
# 2. 是否獨(dú)自旅行 vs 生存率
sns.barplot(x='is_alone', y='survived', data=df, ax=axes[0,1])
axes[0,1].set_title('獨(dú)自旅行與生存率')
axes[0,1].set_xticklabels(['否', '是'])
# 3. 年齡分布(按生存狀態(tài))
df[df['survived']==1]['age'].hist(alpha=0.7, label='生存', ax=axes[1,0])
df[df['survived']==0]['age'].hist(alpha=0.7, label='遇難', ax=axes[1,0])
axes[1,0].set_title('年齡分布對比')
axes[1,0].legend()
# 4. 票價(jià)分布(對數(shù)尺度)
df.boxplot(column='fare', by='survived', ax=axes[1,1])
axes[1,1].set_yscale('log')
axes[1,1].set_title('票價(jià)分布(對數(shù)尺度)')
plt.tight_layout()
plt.show()
關(guān)鍵洞察:
- 頭等艙(pclass=1)生存率最高;
- 結(jié)伴旅行者生存率更高;
- 兒童(<10歲)生存率明顯提升;
- 高票價(jià)乘客更可能生存(可能與艙位相關(guān))。
?? 這些洞察可直接用于后續(xù)的機(jī)器學(xué)習(xí)建模——例如,
pclass、is_alone、age都是強(qiáng)預(yù)測特征。
七、常見陷阱與最佳實(shí)踐
1. 不要濫用inplace=True
雖然 df.dropna(inplace=True) 看似方便,但它會(huì)直接修改原數(shù)據(jù),難以回溯。建議:
df_clean = df.dropna() # 顯式創(chuàng)建新對象
2. 避免鏈?zhǔn)剿饕–hained Indexing)
錯(cuò)誤寫法:
df[df['age'] > 30]['fare'] = 100 # 可能報(bào) SettingWithCopyWarning
正確寫法:
df.loc[df['age'] > 30, 'fare'] = 100
3. 可視化前先檢查數(shù)據(jù)分布
- 對長尾分布(如票價(jià))使用對數(shù)尺度;
- 對分類變量確保類別不多(否則圖表混亂);
- 添加標(biāo)題、坐標(biāo)軸標(biāo)簽、圖例——否則別人看不懂。
4. 保持代碼可復(fù)現(xiàn)
- 設(shè)置隨機(jī)種子:
np.random.seed(42) - 記錄 Pandas/NumPy 版本(不同版本行為可能不同)
八、下一步:為機(jī)器學(xué)習(xí)做準(zhǔn)備
通過本文,你已經(jīng)掌握了:
- 用 NumPy 高效處理數(shù)值;
- 用 Pandas 清洗、轉(zhuǎn)換、探索表格數(shù)據(jù);
- 用 Matplotlib/Seaborn 可視化發(fā)現(xiàn)規(guī)律。
接下來,在第三篇文章中,我們將深入探討:
- 數(shù)據(jù)質(zhì)量的五大維度(完整性、一致性、準(zhǔn)確性等);
- 更高級(jí)的缺失值處理策略(插值、模型預(yù)測填充);
- 異常值檢測與處理;
- 特征縮放(標(biāo)準(zhǔn)化、歸一化)的必要性。
這些內(nèi)容將直接決定你未來模型的上限。
行動(dòng)建議
- 動(dòng)手運(yùn)行本文所有代碼,不要只看;
- 嘗試用 Pandas 分析你自己的數(shù)據(jù)(如運(yùn)動(dòng)記錄、賬單、課程成績);
- 在 Kaggle 上下載一個(gè)新數(shù)據(jù)集(如 House Prices),重復(fù)本文流程;
- 把你的 Notebook 上傳到 GitHub,形成第一個(gè)數(shù)據(jù)作品。
記?。?strong>工具的價(jià)值不在“知道”,而在“用過”。
你敲下的每一行代碼,都在為未來的智能系統(tǒng)鋪路。
到此這篇關(guān)于Python與數(shù)據(jù)科學(xué)工具鏈之NumPy、Pandas、Matplotlib快速上手的文章就介紹到這了,更多相關(guān)Python NumPy、Pandas、Matplotlib上手內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python中2種常用數(shù)據(jù)可視化庫Bokeh和Altair使用示例詳解
- 使用Python的數(shù)據(jù)可視化庫Matplotlib實(shí)現(xiàn)折線圖
- 探索Python數(shù)據(jù)可視化庫中Plotly Express的使用方法
- Python數(shù)據(jù)可視化庫seaborn的使用總結(jié)
- Python使用Matplotlib繪制專業(yè)柱狀圖的完整指南
- Python安裝Matplotlib庫的五種方法小結(jié)
- Python?seaborn數(shù)據(jù)可視化繪圖(直方圖,密度圖,散點(diǎn)圖)
- Python利用Seaborn繪制多標(biāo)簽的混淆矩陣
- python使用seaborn繪圖直方圖displot,密度圖,散點(diǎn)圖
- python使用Plotly創(chuàng)建交互式數(shù)據(jù)可視化的操作步驟
- 詳解如何使用Python的Plotly庫進(jìn)行交互式圖形可視化
- Python使用Plotly繪制常見5種動(dòng)態(tài)交互式圖表
- Python 數(shù)據(jù)可視化之Bokeh詳解
- 淺談python可視化包Bokeh
- Python數(shù)據(jù)可視化庫:Matplotlib、Seaborn、Plotly、Bokeh等對比與選擇
相關(guān)文章
2018年P(guān)ython值得關(guān)注的開源庫、工具和開發(fā)者(總結(jié)篇)
本文給大家總結(jié)了2018年P(guān)ython值得關(guān)注的開源庫、工具和開發(fā)者,需要的朋友可以參考下2018-01-01
python-xpath獲取html文檔的部分內(nèi)容
這篇文章主要介紹了python-xpath獲取html文檔的部分內(nèi)容,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
python+matplotlib演示電偶極子實(shí)例代碼
這篇文章主要介紹了python+matplotlib演示電偶極子實(shí)例代碼,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01
詳解windows python3.7安裝numpy問題的解決方法
這篇文章主要介紹了windows python3.7安裝numpy問題的解決方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-08-08
Pycharm連接遠(yuǎn)程服務(wù)器并遠(yuǎn)程調(diào)試的全過程
PyCharm 是 JetBrains 開發(fā)的一款 Python 跨平臺(tái)編輯器,下面這篇文章主要介紹了Pycharm連接遠(yuǎn)程服務(wù)器并遠(yuǎn)程調(diào)試的全過程,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2021-06-06

