【问题标题】:Merging a list of dataframes with the same index合并具有相同索引的数据框列表
【发布时间】:2021-07-21 17:45:23
【问题描述】:

我将通过在同一行中填充 NaN 值列来将数据框列表合并为一个。数据框也具有相同的索引。

df

        A       B
0       Red     Blue
1       Green   Red

df1

        A       B    Value1  Value2
0       Red     Blue    1.0   NaN
1       Green   Red     NaN   0.2

df2


       A        B     Value1    Value2
1      Green    Red    3.0      NaN
0      Red      Blue   NaN      0.15

代码

df_list = [df1, df2]

df_final = pd.merge(df, df_list, left_index=True, right_index=True)

但是得到了这个错误TypeError: Can only merge Series or DataFrame objects, a <class 'list'> was passed

预期输出


        A      B    Value1  Value2
0       Red    Blue   1     0.15
1       Green  Red    3     0.20

【问题讨论】:

  • df_list 不是数据框,它是数据框列表...
  • df_list 全名将是 list_of_dataframes,您正在尝试在列表和数据框上使用 pd.merge。可能你在pd.merge之前需要pd.concat[df_list]

标签: python pandas dataframe


【解决方案1】:

你可以用functools.reduce重复调用combine_first

from functools import reduce

df_final = reduce(pd.DataFrame.combine_first, df_list, df)

它以df作为初始值开始,然后使用来自df_list的帧累积调用combine_first以给出最终帧。

>>> df_final

       A     B  Value1  Value2
0    Red  Blue     1.0    0.15
1  Green   Red     3.0    0.20

【讨论】:

    猜你喜欢
    • 2020-11-27
    • 2021-03-06
    • 1970-01-01
    • 2020-02-05
    • 2016-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    相关资源
    最近更新 更多