pandas 相当于 R 的 cbind(concatenate/stack 垂直向量)

pandas equivalent of R's cbind (concatenate/stack vectors vertically)

假设我有两个数据帧:

import pandas
....
....
test1 = pandas.DataFrame([1,2,3,4,5])
....
....
test2 = pandas.DataFrame([4,2,1,3,7])
....

我试过 test1.append(test2) 但它相当于 R 的 rbind

如何将两者合并为数据框的两列,类似于 R 中的 cbind 函数?

test3 = pd.concat([test1, test2], axis=1)
test3.columns = ['a','b']

pandas 中的 concat(axis = 1) 和 R 中的 cbind() 之间有一个关键区别:

concat尝试通过索引merge/align。 R 数据框中没有索引的概念。如果两个 pandas 数据帧的索引未对齐,则结果与 cbind 不同(即使它们具有相同的行数)。您需要确保索引对齐或 drop/reset 索引。

示例:

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