Pandas如何在不丢失列标题的情况下连接两个数据帧

Pri*_*ank 7 python pandas

我有以下玩具代码:

 import pandas as pd
 df = pd.DataFrame()
 df["foo"] = [1,2,3,4]

 df2 = pd.DataFrame()
 df2["bar"]=[4,5,6,7]  

 df = pd.concat([df,df2], ignore_index=True,axis=1)
 print(list(df))
Run Code Online (Sandbox Code Playgroud)

输出:[0,1]
预期输出:( [foo,bar]顺序并不重要)
如果可以保证标题是唯一的,是否有任何方法可以连接两个数据帧而不会丢失原始列标题?
我想到迭代列然后将它们添加到其中一个DataFrame中,但有没有pandas函数或concat我不知道的参数?

谢谢!

umu*_*tto 10

merge,join和concat文档中所述,忽略index将删除所有名称引用并使用范围(0 ... n-1).因此,一旦删除ignore_index参数或将其设置为false(默认值),它应该为您提供所需的结果.

df = pd.concat([df, df2], axis=1)
Run Code Online (Sandbox Code Playgroud)

这将基于索引连接您的df和df2(相同的索引行将被连接,如果其他数据帧没有该索引的成员,它将被连接为nan).

如果您对数据帧有不同的索引,并希望以这种方式连接它.您可以创建临时索引并加入,也可以在使用concat(...,ignore_index = True)后设置新数据框的列.