[英]Merging a list of dataframes with the same index
I would merge a list of dataframes into one, by filling NaN values columns in the same row.通过在同一行中填充 NaN 值列,我会将数据框列表合并为一个。 The dataframes have the same index as well.
数据帧也具有相同的索引。
df df
A B
0 Red Blue
1 Green Red
df1 df1
A B Value1 Value2
0 Red Blue 1.0 NaN
1 Green Red NaN 0.2
df2 df2
A B Value1 Value2
1 Green Red 3.0 NaN
0 Red Blue NaN 0.15
Code代码
df_list = [df1, df2]
df_final = pd.merge(df, df_list, left_index=True, right_index=True)
But got this error TypeError: Can only merge Series or DataFrame objects, a <class 'list'> was passed
但是得到这个错误
TypeError: Can only merge Series or DataFrame objects, a <class 'list'> was passed
Expected Output预期产出
A B Value1 Value2
0 Red Blue 1 0.15
1 Green Red 3 0.20
You can repeatedly call combine_first
with functools.reduce
:您可以使用
functools.reduce
重复调用combine_first
:
from functools import reduce
df_final = reduce(pd.DataFrame.combine_first, df_list, df)
which starts with df
as the initial value and then accumulatively invokes combine_first
with frames from df_list
to give a final frame.它以
df
作为初始值开始,然后使用combine_first
中的帧累积调用df_list
以给出最终帧。
>>> df_final
A B Value1 Value2
0 Red Blue 1.0 0.15
1 Green Red 3.0 0.20
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.