假设我有两个数据框:
import pandas as pd
test1 = pd.DataFrame([1,2,3,4,5])
test2 = pd.DataFrame([4,2,1,3,7])
我尝试过
test1.append(test2)
,但它相当于R的rbind
。
如何将两者组合为数据框的两列,类似于 R 中的
cbind
函数?
test3 = pd.concat([test1, test2], axis=1)
test3.columns = ['a','b']
(但请参阅下面@feng-mai的详细回答)
pandas 中的
concat(axis = 1)
和 R 中的 cbind()
之间有一个关键区别:
concat
尝试按索引合并/对齐。 R 数据帧中没有索引的概念。如果两个 pandas 数据帧的索引未对齐,则结果与 cbind 不同(即使它们具有相同的行数)。您需要确保索引对齐或删除/重置索引。
示例:
import pandas as pd
test1 = pd.DataFrame([1,2,3,4,5])
test1.index = ['a','b','c','d','e']
test2 = pd.DataFrame([4,2,1,3,7])
test2.index = ['d','e','f','g','h']
pd.concat([test1, test2], axis=1)
0 0
a 1.0 NaN
b 2.0 NaN
c 3.0 NaN
d 4.0 4.0
e 5.0 2.0
f NaN 1.0
g NaN 3.0
h NaN 7.0
pd.concat([test1.reset_index(drop=True), test2.reset_index(drop=True)], axis=1)
0 1
0 1 4
1 2 2
2 3 1
3 4 3
4 5 7
pd.concat([test1.reset_index(), test2.reset_index(drop=True)], axis=1)
index 0 0
0 a 1 4
1 b 2 2
2 c 3 1
3 d 4 3
4 e 5 7