# Pandas數據結構的介紹及如何創建Series,DataFrame對象
## 一、Pandas簡介
### 1.1 Pandas概述
Pandas是Python中最流行的數據分析庫之一,由Wes McKinney于2008年開發。名稱"Pandas"源自"Panel Data"(面板數據)的縮寫。作為NumPy的擴展庫,Pandas專門為解決數據分析任務而設計,尤其擅長處理以下類型的數據:
- 表格數據(如SQL表格、Excel表格)
- 時間序列數據
- 異構數據(不同類型的數據列)
- 帶標簽的數據(行列都有標識)
### 1.2 Pandas的核心優勢
1. **高效處理**:基于NumPy實現,運算性能優異
2. **靈活索引**:支持復雜的行列索引操作
3. **缺失值處理**:內置完善的缺失值處理方法
4. **數據對齊**:自動按標簽對齊不同數據源
5. **豐富IO**:支持CSV、Excel、SQL、JSON等多種數據格式
### 1.3 安裝與導入
```python
# 安裝命令
pip install pandas
# 標準導入方式
import pandas as pd
Series是Pandas中最基本的一維數據結構,可以看作帶標簽的數組。其特點包括:
+--------+-----------+
| Index | Values |
+--------+-----------+
| 0 | 'A' |
| 1 | 'B' |
| 2 | 'C' |
+--------+-----------+
DataFrame是Pandas中最常用的二維表格型數據結構,特點包括:
+--------+-----------+-----------+-----------+
| Index | Column A | Column B | Column C |
+--------+-----------+-----------+-----------+
| 0 | 1 | 'X' | True |
| 1 | 2 | 'Y' | False |
+--------+-----------+-----------+-----------+
import pandas as pd
# 基本創建(自動生成數字索引)
s1 = pd.Series([1, 3, 5, 7])
print(s1)
# 自定義索引
s2 = pd.Series([10, 20, 30], index=['a', 'b', 'c'])
print(s2)
data = {'北京': 2154, '上海': 2428, '廣州': 1867}
s3 = pd.Series(data)
print(s3)
dates = pd.date_range('20230101', periods=4)
s4 = pd.Series([1.2, 3.4, 5.6, 7.8], index=dates)
s5 = pd.Series([1, None, 3, np.nan])
s = pd.Series([10, 20, 30], index=['a', 'b', 'c'])
print(s.values) # 值數組 [10 20 30]
print(s.index) # 索引對象 Index(['a', 'b', 'c'])
print(s.dtype) # 數據類型 int64
print(s.shape) # 形狀 (3,)
print(s.size) # 元素數量 3
print(s.name) # 名稱 None
data = {
'城市': ['北京', '上海', '廣州'],
'人口(萬)': [2154, 2428, 1867],
'GDP(億)': [40269, 43214, 28232]
}
df1 = pd.DataFrame(data)
print(df1)
df2 = pd.DataFrame(
data,
index=['a', 'b', 'c'], # 行索引
columns=['城市', 'GDP(億)'] # 選擇/排序列
)
arr = np.random.rand(3, 4)
df3 = pd.DataFrame(arr, columns=list('ABCD'))
data = [
['北京', 2154, 40269],
['上海', 2428, 43214]
]
df4 = pd.DataFrame(data, columns=['城市', '人口', 'GDP'])
s1 = pd.Series([2154, 2428, 1867])
s2 = pd.Series([40269, 43214, 28232])
df5 = pd.DataFrame({'人口': s1, 'GDP': s2})
dates = pd.date_range('20230101', periods=6)
df6 = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
arrays = [
['A', 'A', 'B', 'B'],
[1, 2, 1, 2]
]
index = pd.MultiIndex.from_arrays(arrays, names=('字母', '數字'))
df7 = pd.DataFrame(np.random.randn(4, 3), index=index, columns=['X', 'Y', 'Z'])
df = pd.DataFrame({'A': [1,2], 'B': [3,4]})
print(df.shape) # 形狀 (2,2)
print(df.index) # 行索引 RangeIndex(start=0, stop=2, step=1)
print(df.columns) # 列索引 Index(['A', 'B'])
print(df.dtypes) # 每列數據類型
print(df.values) # 二維ndarray
print(df.T) # 轉置
s = pd.Series([10, 20, 30], index=['a', 'b', 'c'])
# 標簽索引
print(s['a']) # 10
# 位置索引
print(s.iloc[0]) # 10
# 布爾索引
print(s[s > 15]) # b 20, c 30
df = pd.DataFrame({'A': [1,2,3], 'B': [4,5,6]})
# 列選擇
print(df['A']) # 獲取A列
# 行選擇
print(df.loc[0]) # 第一行
print(df.iloc[0:2]) # 前兩行
# 行列組合
print(df.loc[0, 'A']) # 1
df['C'] = df['A'] + df['B'] # 新增列
df['A'] = [10, 20, 30] # 修改列
# 刪除列
df.drop('A', axis=1, inplace=True)
# 刪除行
df.drop([0,1], axis=0, inplace=True)
# 創建含缺失值的數據
df = pd.DataFrame({
'A': [1, None, 3],
'B': [None, 5, 6]
})
# 填充缺失值
df_filled = df.fillna({'A': df['A'].mean(), 'B': 0})
# 創建銷售數據
sales = pd.DataFrame({
'日期': pd.date_range('20230101', periods=5),
'產品': ['A', 'B', 'A', 'C', 'B'],
'銷量': [120, 150, 80, 200, 90]
})
# 按產品匯總
summary = sales.groupby('產品')['銷量'].sum()
Pandas的Series和DataFrame為數據分析提供了強大的基礎工具。通過本文的學習,您應該已經掌握:
建議讀者通過實際數據集練習這些操作,逐步掌握Pandas的強大功能。后續可以進一步學習: - 數據清洗與預處理 - 數據聚合與分組操作 - 時間序列處理 - 性能優化技巧 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。