有一个有趣的trending question在 r ,它是这样的:
I have this df1:
A B C 1 2 3 5 7 9where
A B Care columns names.I have another df2 with one column:
A 1 2 3 4I would like to append df2 for each column of df1, creating this final dataframe:
A B C 1 2 3 5 7 9 1 1 1 2 2 2 3 3 3 4 4 4is it possible to do it?
我想知道,这在 Pandas 中是如何完成的?
我在下面发布了我自己的解决方案,但我也在寻找其他更好的替代方案!
请您参考如下方法:
选项 1
应用
df1.apply(pd.Series.append, to_append=df2.A)
A B C
0 1 2 3
1 5 7 9
0 1 1 1
1 2 2 2
2 3 3 3
3 4 4 4
选项 2
numpy.vstack 和 numpy.tile
pd.DataFrame(
np.vstack([df1, np.tile(df2, df1.shape[1])]),
columns=df1.columns
)
A B C
0 1 2 3
1 5 7 9
2 1 1 1
3 2 2 2
4 3 3 3
5 4 4 4
