【问题标题】:Pandas: How to concatenate dataframes in the following manner?Pandas:如何以下列方式连接数据帧?
【发布时间】:2018-11-23 19:25:27
【问题描述】:

我想将多个数据帧连接成一个数据帧。以下示例说明了我希望串联发生的方式:

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

我想知道这是否可以使用 pandas.concat 命令来完成。我知道这可以通过 pd.merge 命令完成。
谢谢。

【问题讨论】:

  • 是的,可以通过pd.concat([df1.set_index(['A','B']), df2.set_index(['A','B'])])
  • Pandas 网站上有关于 pandas.concat 函数的大量文档。 pandas.concat() 页面特别有几个使用 pandas.concat 的示例。
  • @David 我读了那个页面,它有很好的文档记录,但我找不到如何使用 pd.concat 来做到这一点,他们为 pd.merge 做到了。

标签: python pandas dataframe concatenation


【解决方案1】:

set_indexMultiIndex 的列表理解一起使用,然后使用concat

dfs = [df1, df2, df3]

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    • 2018-02-08
    相关资源
    最近更新 更多