Pandas: How to concatenate dataframes in the following manner?

旧城冷巷雨未停 提交于 2019-12-02 05:52:26

问题


I want to concatenate multiple dataframes into one dataframe. The manner I want the concatenation to happen is illustrated in the following example:

Input tables:
   A  B  C  D
0  x  p  2  4
1  y  q  3  5

   A  B  E  F
0  x  p  6  8
1  y  q  9  10

Output table:

   A  B  C  D  E  F
0  x  p  2  4  6  8
1  y  q  3  5  9  10

I want to know if this can be done using the pandas.concat command. I know this can be done through the pd.merge command.
Thanks.


回答1:


Use set_index with list comprehension for MultiIndex and then concat:

dfs = [df1, df2, df3]

df = pd.concat([x.set_index(['A','B']) for x in dfs], axis=1)


来源:https://stackoverflow.com/questions/50850337/pandas-how-to-concatenate-dataframes-in-the-following-manner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!