简体   繁体   English

在 pandas 中连接两个具有不同列的数据帧

[英]Concat two dataframes with different columns in pandas

How do I concat two dataframes with different columns in pandas, passing the column header also as row into the new dataframe which will have not headers.如何在 pandas 中连接两个具有不同列的数据帧,将列 header 也作为行传递到没有标题的新 dataframe 中。 result_df is the desired format result_df 是所需的格式

similar issue here the column count remains same, which is not what is desired here 类似的问题,列数保持不变,这不是这里想要的

>df_may

  id  quantity  attr_1  attr_2
0  1        20       0       1
1  2        23       1       1
2  3        19       1       1
3  4        19       0       0

>df_jun

  id2  quantity2  attr_12  
0  5         8       1       
1  6        13       0       
2  7        20       1       
3  8        25       1       

>result_df
0 id  quantity  attr_1  attr_2
1  1        20       0       1
2  2        23       1       1
3  3        19       1       1
4  4        19       0       0
5 id2  quantity2  attr_12  
6  5         8       1       
7  6        13       0       
8  7        20       1       
9  8        25       1       

did you try?你试过了吗?

merged = pandas.concat(
    [df_may, df_jun.rename(columns={"id2": "id", "quantity2": "quantity", "attr_12": "attr_1"})],
    ignore_index=True,
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM