pandas 的 concat() 用來把多個 DataFrame 拼在一起。以下 7 個例子涵蓋常見用法:上下/左右堆疊、欄位對齊、重複欄位、多層 key。
Example 1:基本 concat — 將兩個 DataFrame 上下堆疊(axis=0,預設值) #
import pandas as pd
df1 = pd.DataFrame({
'Name':['Alice', 'Bob'],
'Score':[80,90]
})
df2 = pd.DataFrame({
'Name':['Cat', 'David'],
'Score':[70,85]
})
df3 = pd.DataFrame({
'Age':[25, 30],
'City':['HK', 'Sydney']
})
result = pd.concat([df1, df2])
print (result)output:
Name Score 0 Alice 80 1 Bob 90 0 Cat 70 1 David 85
Example 2:用 axis=1 左右並排 #
import pandas as pd
df1 = pd.DataFrame({
'Name':['Alice', 'Bob'],
'Score':[80,90]
})
df2 = pd.DataFrame({
'Name':['Cat', 'David'],
'Score':[70,85]
})
df3 = pd.DataFrame({
'Age':[25, 30],
'City':['HK', 'Sydney']
})
# result = pd.concat([df1, df2])
result = pd.concat([df1, df3], axis=1)
print (result)output:
Name Score Age City 0 Alice 80 25 HK 1 Bob 90 30 Sydney
Example 3:欄位不同時 concat — 缺少的位置補上 NaN #
import pandas as pd
df1 = pd.DataFrame({
'Name':['Alice', 'Bob'],
'Score':[80,90]
})
df2 = pd.DataFrame({
'Name':['Cat', 'David'],
'Score':[70,85]
})
df3 = pd.DataFrame({
'Age':[25, 30],
'City':['HK', 'Sydney']
})
df4 = pd.DataFrame({
'Name':['Eric'],
'Age':[40]
})
# result = pd.concat([df1, df2])
result = pd.concat([df1, df4], axis=0)
print (result)output:
Name Score Age 0 Alice 80.0 NaN 1 Bob 90.0 NaN 0 Eric NaN 40.0
Example 4:concat 後 reset_index — 整理重複的索引 #
import pandas as pd
df1 = pd.DataFrame({
'Name':['Alice', 'Bob']
})
df2 = pd.DataFrame({
'Name':['Cat', 'David']
})
result = pd.concat([df1, df2]).reset_index(drop=True)
print (result)output:
Name 0 Alice 1 Bob 2 Cat 3 David
Example 5:axis=1 且兩邊都有 'B' 欄 — 結果出現兩個 'B' 欄位 #
import pandas as pd
df1 = pd.DataFrame({
'A':[1,2,3],
'B':[3,4,4]
})
df2 = pd.DataFrame({
'B':[5,6],
'D':[7,8]
})
result = pd.concat([df1, df2], axis=1)
print (result)output:
A B B D 0 1 3 5.0 7.0 1 2 4 6.0 8.0 2 3 4 NaN NaN
Example 6:先重新命名欄位,避免重複 #
import pandas as pd
df1 = pd.DataFrame({
'A':[1,2],
'B':[3,4]
})
df2 = pd.DataFrame({
'B':[5,6],
'D':[7,8]
})
# result = pd.concat([df1, df2], axis=1)
df2_renamed = df2.rename(columns={'B':'B2'})
pd.concat ([df1, df2_renamed], axis=1)
# print (result)output:
A B B2 D 0 1 3 5 7 1 2 4 6 8
Example 7:用 keys 加上頂層標籤(multi-index) #
#Concat with multi-Column
import pandas as pd
df1 = pd.DataFrame({
'A':[1,2],
'B':[3,4]
})
df2 = pd.DataFrame({
'B':[5,6],
'D':[7,8]
})
df3 = pd.DataFrame({
'B':[5,6],
'D':[7,8]
})
dfNew = pd.concat([df1,df2,df3], axis=1, keys=['df1','df2','df3'])
dfNew
print(dfNew['df1'][dfNew['df1']['B'] > 3]['B'])output:
df1 df2 df3 A B B D B D 0 1 3 5 7 5 7 1 2 4 6 8 6 8 1 4 Name: B, dtype: int64
