Python Pandas 創建 DataFrame 的四種方法
Pandas 是 Python 的一個數據分析包,最初由 AQR Capital Management 於 2008 年 4 月開發,並於 2009 年底開源出來,目前由專註於 Python 數據包開發的 PyData 開發團隊繼續開發和維護,屬於 PyData 項目的一部分。
Pandas 最初被作為金融數據分析工具而開發出來,因此,pandas 為時間序列分析提供了很好的支持。
Pandas 的名稱來自於面板數據(panel data)和 Python 數據分析(data analysis)。
在深度學習中 Pandas 的使用也非常多!
Pandas 數據框架的創建方式
一、創建一個空的數據框架
import pandas as pd
df = pd.DataFrame()
print(df)
運行結果:
Empty DataFrame
Columns: []
Index: []
二、從列表進行創建
- 一維列表
data = [1,2,3,4,5]
df = pd.DataFrame(data) # 將列表數據轉化為 一列
print(df)
運行結果:
0
0 1
1 2
2 3
3 4
4 5
- 二維列表
data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=['Name','Age']) # 將第一維度數據轉為為行,第二維度數據轉化為列,即 3 行 2 列,並設置列標籤
print(df)
運行結果:
Name Age
0 Alex 10
1 Bob 12
2 Clarke 13
- 設置數據格式
data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=['Name','Age'],dtype=float) # 將數字元素 自動轉化為 浮點數
print(df)
運行結果:
Name Age
0 Alex 10.0
1 Bob 12.0
2 Clarke 13.0
三、從 ndarrays / Lists 的 字典創建
- 默認的 index
data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]} # 兩組列元素,並且個數需要相同
df = pd.DataFrame(data) # 這裡默認的 index 就是 range(n),n 是列表的長度
print(df)
運行結果:
Name Age
0 Tom 28
1 Jack 34
2 Steve 29
3 Ricky 42
- 指定 index
data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data, index=['rank1','rank2','rank3','rank4']) # 這裡設定了 index 個數要和列表長度一致
print(df)
運行結果:
Name Age
rank1 Tom 28
rank2 Jack 34
rank3 Steve 29
rank4 Ricky 42
四、從 字典組成的列表 創建
- 自動添加 NaN
data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}] # 列表對應的是第一維,即行,字典為同一行不同列元素
df = pd.DataFrame(data) # 第 1 行 3 列沒有元素,自動添加 NaN (Not a Number)
print(df)
運行結果:
a b c
0 1 2 NaN
1 5 10 20.0
- 取特定的表頭下的列元素
data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]
#With two column indices, values same as dictionary keys
df1 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b']) # 指定表頭都存在於 data,只取部分
#With two column indices with one index with other name
df2 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b1']) # 指定表頭中 b1 不存在,添加 b1 列,元素 NaN
print(df1)
print(df2)
運行結果:
a b
first 1 2
second 5 10
a b1
first 1 NaN
second 5 NaN
五、從 Series 組成的字典 創建
d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
# index 與序列長度相投
# 字典不同的 key 代表一個列的表頭,pd.Series 作為 value 作為該列的元素
df = pd.DataFrame(d)
print(df)
運行結果:
one two
a 1.0 1
b 2.0 2
c 3.0 3
d NaN 4