【问题标题】:Merge a list of DataFrames on particular column合并特定列上的 DataFrame 列表
【发布时间】:2018-09-09 11:35:22
【问题描述】:

假设我在一个列表中有 3 个 DataFrame: df_list = [df1, df2, df3]

每个DataFrame看起来像这样:

df1

puid  ean  color  temp  material 
1111  foob blue   12    metal

df2

puid  ean  color  weight
2222  bazb red    45

df3

puid  ean  height  length  weight
3333  booz 123     344     12

您会注意到每个列中都有唯一的列名。我需要一种将这三个 DataFrame 合并在一起的方法,以便合并后的 DataFrame 如下所示:

合并的 DF

puid  ean  color  temp  material  weight  length  height
1111  foob blue   12    metal     NaN     NaN     NaN
2222  bazb red    NaN   NaN       45      NaN     NaN
3333  booz NaN    NaN   NaN       12      344     123

列的顺序不是那么重要;但至少应该从 puid 开始。

我尝试过使用:pd.concat(df_list, axis=1) 但它只产生一个连接的数据帧(惊喜)

还尝试使用:reduce(lambda x, y: pd.merge(x, y, on = 'puid'), df_list),但由于某种原因,我返回了一个空数据框,并且它没有正确合并(例如,它保留 color_x,color_y)。

任何帮助都会很棒!谢谢:)

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    你说pd.concat(axis=1) 不起作用,但pd.concat((df1,df2,df3)) 起作用:

      color   ean  height  length material  puid  temp  weight
    0  blue  foob     NaN     NaN    metal  1111  12.0     NaN
    0   red  bazb     NaN     NaN      NaN  2222   NaN    45.0
    0   NaN  booz   123.0   344.0      NaN  3333   NaN    12.0
    

    【讨论】:

    • 你是对的!我删除了axis = 1,它工作得很好。因为我有一个大约 15 个 DataFrame 的列表,所以我使用了这样的列表理解:pd.concat([x for x in df_list])。
    • 为了澄清 OP,如果未指定,默认为 axis=0,这就是您所需要的。 axis=1 沿列连接,axis=0 沿索引连接。
    • @QubitZ: [x for x in df_list]df_list 相同。
    • 谢谢大家。通常对我来说,最简单的事情就是问题!
    猜你喜欢
    • 2022-01-24
    • 2018-10-02
    • 2018-05-09
    • 2013-09-21
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    相关资源
    最近更新 更多