为了演示方便,先创建两个DataFrame:
import pandas as pd
x = {
'A': ('a1', 'a2', 'a3'),
'B': ('b1', 'b2', 'b3'),
'C': ('c1', 'c2', 'c3'),
}
y = {
'D': ('d1', 'd2', 'd3'),
'E': ('e1', 'e2', 'e3'),
'F': ('f1', 'f2', 'f3'),
}
index = ['索引1', '索引2', '索引3']
dfx = pd.DataFrame(x, index=index)
dfy = pd.DataFrame(y, index=index)
print(dfx,'\n',dfy)
A B C
索引1 a1 b1 c1
索引2 a2 b2 c2
索引3 a3 b3 c3
D E F
索引1 d1 e1 f1
索引2 d2 e2 f2
索引3 d3 e3 f3
该例子的两个DataFrame具有相同的索引但不同的列名, 所以要横向合并。
join()
)直接使用.join()
函数即可:
>>> dfx.join(dfy)
A B C D E F
索引1 a1 b1 c1 d1 e1 f1
索引2 a2 b2 c2 d2 e2 f2
索引3 a3 b3 c3 d3 e3 f3
x = {
'A': ('a1', 'a2', 'a3'),
'B': ('b1', 'b2', 'b3'),
'C': ('c1', 'c2', 'c3'),
}
y = {
'A': ('d1', 'd2', 'd3'),
'B': ('e1', 'e2', 'e3'),
'C': ('f1', 'f2', 'f3'),
}
index1 = ['索引1', '索引2', '索引3']
index2 = ['索引4', '索引5', '索引6']
dfx = pd.DataFrame(x, index=index1)
dfy = pd.DataFrame(y, index=index2)
print(dfx, '\n' ,dfy)
A B C
索引1 a1 b1 c1
索引2 a2 b2 c2
索引3 a3 b3 c3
A B C
索引4 d1 e1 f1
索引5 d2 e2 f2
索引6 d3 e3 f3
两个DataFrame具有相同的列名但不同的索引, 所以要竖向追加。
有更新
>>> dfx.append(dfy)
A B C
索引1 a1 b1 c1
索引2 a2 b2 c2
索引3 a3 b3 c3
索引4 d1 e1 f1
索引5 d2 e2 f2
索引6 d3 e3 f3
append()
方法对带有MultiIndex(即多级索引)的DataFrame也是可以使用的,只要保证两个df的列名相同,且两个df的MultiIndex级数相同。
前面说的append()
似乎在新版本的pandas里被弃用了,并提供了新的方法concat()
:
import pandas as pd
pd.concat([df1,df2,...])