Pandas數據結構詳解:Series與DataFrame實戰指南
前言
Pandas是Python數據分析的核心庫,其強大的數據處理能力主要基于兩種核心數據結構:Series和DataFrame。本文將深入解析這兩種數據結構的概念、創建方式、常用屬性和方法,并通過豐富的實戰案例幫助讀者掌握Pandas的基礎操作。
一、Series數據結構詳解
1.1 Series概念與特點
Series是Pandas中的一維數據結構,可以理解為帶標簽的一維數組。每個Series對象包含兩個主要組成部分:
- 數據值(Values):一組值,支持NumPy的所有數據類型
- 索引(Index):與數據值對應的標簽,類似于字典的鍵
核心特點:
- 類似于Excel中的一列數據
- 支持通過標簽訪問數據
- 自動創建從0開始的整數索引(如果未指定)
1.2 Series的創建方式
方式一:通過NumPy數組創建
import numpy as np
import pandas as pd# 創建ndarray對象
arr = np.array([1, 2, 3, 4, 5])
print(arr) # [1 2 3 4 5]# 轉換為Series對象
s1 = pd.Series(arr)
print(s1)
# 輸出:
# 0 1
# 1 2
# 2 3
# 3 4
# 4 5
# dtype: int64
方式二:通過Python列表創建
# 直接傳入列表
s2 = pd.Series([1, 2, 3, 4, 5])
print(s2)# 指定自定義索引
s3 = pd.Series([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e'])
print(s3)
# 輸出:
# a 1
# b 2
# c 3
# d 4
# e 5
# dtype: int64
方式三:通過字典創建
# 字典的鍵自動成為索引
s4 = pd.Series({'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5})
print(s4)
1.3 Series的常用屬性
# 創建示例Series
s = pd.Series([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e'])# 基本屬性
print(s.dtype) # 數據類型:int64
print(s.shape) # 維度:(5,)
print(s.size) # 元素個數:5
print(s.index) # 索引:Index(['a', 'b', 'c', 'd', 'e'], dtype='object')
print(s.values) # 值:array([1, 2, 3, 4, 5])
print(s.name) # 名稱:None
1.4 Series的常用方法
統計方法
s = pd.Series([1, 2, 3, 4, 2, 3], index=['a', 'b', 'c', 'd', 'e', 'f'])# 基礎統計
print(s.count()) # 非空元素個數:6
print(s.sum()) # 總和:15
print(s.mean()) # 平均值:2.5
print(s.median()) # 中位數:2.5
print(s.mode()) # 眾數:2, 3
print(s.std()) # 標準差:1.0488088481701516
print(s.var()) # 方差:1.1
print(s.min()) # 最小值:1
print(s.max()) # 最大值:4# 描述性統計
print(s.describe())
# 輸出:
# count 6.000000
# mean 2.500000
# std 1.048809
# min 1.000000
# 25% 2.000000
# 50% 2.500000
# 75% 3.000000
# max 4.000000
# dtype: float64
數據操作方法
# 查看數據
print(s.head(3)) # 前3行
print(s.tail(3)) # 后3行# 排序
print(s.sort_values()) # 按值升序
print(s.sort_values(ascending=False)) # 按值降序
print(s.sort_index()) # 按索引升序# 去重和統計
print(s.unique()) # 唯一值:[1 2 3 4]
print(s.value_counts()) # 值計數:2 2, 3 2, 1 1, 4 1
print(s.drop_duplicates()) # 刪除重復值
1.5 Series的布爾索引
# 讀取科學家數據
df = pd.read_csv("data/scientists.csv")
ages_series = df['Age']# 計算平均年齡
mean_age = ages_series.mean()
print(f"平均年齡:{mean_age}") # 59.125# 布爾索引篩選
older_scientists = ages_series[ages_series > mean_age]
print("年齡大于平均年齡的科學家:")
print(older_scientists)# 獲取符合條件的完整信息
older_info = df[ages_series > mean_age][["Name", "Age"]]
print(older_info)
1.6 Series的運算操作
# Series與數值運算
ages_series = df['Age']
print(ages_series + 10) # 每個年齡加10
print(ages_series * 2) # 每個年齡乘2# Series與Series運算
print(ages_series + ages_series) # 對應元素相加# 基于索引的運算
sorted_ages = ages_series.sort_values(ascending=False)
print(ages_series + sorted_ages) # 按索引匹配運算
二、DataFrame數據結構詳解
2.1 DataFrame概念與特點
DataFrame是Pandas中最核心的數據結構,可以理解為二維表格,類似于Excel工作表或SQL數據庫表。
核心特點:
- 二維表格結構(行和列)
- 每列是一個Series對象
- 所有列共享同一個行索引
- 支持多種數據類型的列
2.2 DataFrame的創建方式
方式一:通過字典創建
# 基礎字典創建
dict_data = {'name': ['張三', '李四', '王五'],'age': [18, 19, 20],'sex': ['男', '女', '男']
}df1 = pd.DataFrame(dict_data)
print(df1)
# 輸出:
# name age sex
# 0 張三 18 男
# 1 李四 19 女
# 2 王五 20 男# 指定行索引
df2 = pd.DataFrame(dict_data, index=['a', 'b', 'c'])
print(df2)# 指定行索引和列索引
df3 = pd.DataFrame(dict_data, index=['a', 'b', 'c'], columns=['id', 'name', 'age', 'sex'])
print(df3) # 不存在的列用NaN填充
方式二:通過CSV文件創建
# 讀取CSV文件
df = pd.read_csv("data/scientists.csv")
print(df.head())# 指定索引列
df = pd.read_csv("data/scientists.csv", index_col='id')
print(df.head())
2.3 DataFrame的常用屬性
df = pd.read_csv("data/scientists.csv")# 基本屬性
print(df.index) # 行索引
print(df.columns) # 列名
print(df.values) # 數據值
print(df.shape) # 維度:(8, 5)
print(df.size) # 元素個數:40
print(df.ndim) # 維度數:2
print(df.dtypes) # 每列的數據類型
2.4 DataFrame的常用方法
數據查看方法
print(df.head()) # 前5行
print(df.tail(3)) # 后3行
print(df.info()) # 數據信息
print(df.describe()) # 描述性統計# 按數據類型統計
print(df.describe(exclude=['object'])) # 排除字符串類型
print(df.describe(include='all')) # 包含所有類型
數據篩選方法
# 布爾索引篩選
movie_df = pd.read_csv("data/movie.csv")
long_movies = movie_df[movie_df.duration > movie_df.duration.mean()]
print(long_movies[["director_name", 'duration']].head())# 多條件篩選
result = movie_df[(movie_df.duration > 120) & (movie_df.budget > 50000000)
]
print(result.head())
2.5 DataFrame的列操作
添加列
movie_df = pd.read_csv("data/movie.csv", index_col='movie_title')# 添加簡單列
movie_df['has_seen'] = 0
print(movie_df.head())# 添加計算列
movie_df['director_actor_facebook_likes'] = (movie_df['director_facebook_likes'] +movie_df['actor_1_facebook_likes'] +movie_df['actor_2_facebook_likes'] +movie_df['actor_3_facebook_likes']
)
print(movie_df.head())
刪除列
# 刪除單列
movie_df.drop("has_seen", axis=1, inplace=True)# 刪除多列
movie_df.drop(["actor_1_name", "actor_2_name", "actor_3_name"], axis=1, inplace=True)# 刪除行
movie_df.drop("Avatar", axis=0, inplace=True)
插入列
# 在指定位置插入列
movie_df.insert(0, "profit", movie_df["gross"] - movie_df["budget"])
print(movie_df.head())
2.6 DataFrame的運算操作
# DataFrame與數值運算
print(df * 2) # 每個元素乘2# DataFrame與DataFrame運算
print(df + df) # 對應元素相加# 索引不匹配的運算
print(df + df[0:4]) # 不匹配的索引用NaN填充
三、實戰案例分析
3.1 科學家數據分析
# 讀取數據
scientists_df = pd.read_csv("data/scientists.csv")# 基礎統計
print("科學家年齡統計:")
print(scientists_df['Age'].describe())# 按職業分組統計
occupation_stats = scientists_df.groupby('Occupation')['Age'].agg(['mean', 'count'])
print("\n各職業年齡統計:")
print(occupation_stats)# 篩選長壽科學家
long_lived = scientists_df[scientists_df['Age'] > 70]
print(f"\n年齡超過70歲的科學家:{len(long_lived)}人")
print(long_lived[['Name', 'Age', 'Occupation']])
3.2 餐廳小費數據分析
# 讀取小費數據
tips_df = pd.read_csv("data/tips.csv")# 基礎統計
print("小費數據分析:")
print(f"總賬單平均:${tips_df['total_bill'].mean():.2f}")
print(f"小費平均:${tips_df['tip'].mean():.2f}")
print(f"小費比例:{tips_df['tip'].sum() / tips_df['total_bill'].sum() * 100:.1f}%")# 按性別分析
gender_tips = tips_df.groupby('sex')['tip'].agg(['mean', 'count'])
print("\n按性別分析小費:")
print(gender_tips)# 按星期分析
day_tips = tips_df.groupby('day')['tip'].mean().sort_values(ascending=False)
print("\n按星期分析平均小費:")
print(day_tips)
3.3 電影數據分析
# 讀取電影數據
movie_df = pd.read_csv("data/movie.csv")# 計算利潤率
movie_df['profit_margin'] = ((movie_df['gross'] - movie_df['budget']) / movie_df['budget'] * 100
)# 篩選盈利電影
profitable_movies = movie_df[movie_df['profit_margin'] > 0]
print(f"盈利電影數量:{len(profitable_movies)}")
print(f"盈利電影比例:{len(profitable_movies) / len(movie_df) * 100:.1f}%")# 按導演分析
director_stats = movie_df.groupby('director_name').agg({'profit_margin': 'mean','movie_title': 'count'
}).rename(columns={'movie_title': 'movie_count'})# 篩選多部電影的導演
top_directors = director_stats[director_stats['movie_count'] >= 3].sort_values('profit_margin', ascending=False)
print("\n多部電影導演的利潤率排名:")
print(top_directors.head(10))
四、最佳實踐與注意事項
4.1 性能優化建議
- 使用適當的數據類型:根據數據特點選擇合適的數據類型
- 避免鏈式操作:減少中間變量的創建
- 使用向量化操作:避免使用循環,優先使用Pandas的內置方法
4.2 常見錯誤與解決方案
- SettingWithCopyWarning:使用
.copy()
或.loc
避免鏈式索引 - 數據類型不匹配:注意數值運算時的數據類型轉換
- 索引不匹配:確保運算時索引的一致性
4.3 代碼規范
# 推薦的代碼風格
import pandas as pd
import numpy as np# 讀取數據
df = pd.read_csv("data.csv")# 數據預處理
df_clean = df.dropna().copy()# 數據分析
result = df_clean.groupby('category').agg({'value': ['mean', 'std', 'count']
})# 結果輸出
print(result)
五、總結
本文詳細介紹了Pandas的兩種核心數據結構:Series和DataFrame。通過豐富的代碼示例和實戰案例,我們學習了:
- Series:一維帶標簽數組,支持多種創建方式和強大的統計方法
- DataFrame:二維表格結構,是數據分析的主要工具
- 數據操作:包括篩選、運算、列操作等常用功能
- 實戰應用:通過真實數據集展示了數據分析的完整流程
掌握這些基礎知識后,你將能夠:
- 高效地處理各種格式的數據
- 進行基礎的數據清洗和預處理
- 執行描述性統計分析
- 為更高級的數據分析任務打下堅實基礎
Pandas的強大之處在于其豐富的生態系統和與其他數據科學庫的無縫集成。建議讀者在實際項目中多加練習,逐步掌握更多高級功能。
關鍵詞:Pandas、Series、DataFrame、數據分析、Python、數據科學
相關推薦:
- NumPy基礎入門實戰指南
- MySQL窗口函數與PyMySQL實戰指南
- 數據結構與算法基礎