我有两个数据框:
df_old:
A B C D E
1 b1 c d1 e1
2 b2 c d2 e2
3 b3 c d3 e3
df:
A B C D F
2 b2 c2 d0 f2
4 b4 c1 d4 f4
5 b5 c2 d5 f5
我希望它们合并成什么:
A B C D E F
1 b1 c d1 e1
2 b2 c2 d2 e2 f2
3 b3 c d3 e3
4 b4 c1 d4 f4
5 b5 c2 d5 f5
我使用这段代码,但是当涉及到省略的行时会出现问题,例如 df['A'] 第 1 行和第 3 行:
df1 = df_old.loc[:,df_old.columns != 'C']
df2 = df.loc[:len(df_old)-1, df.columns != 'B']
df2 = df2.loc[:, df2.columns != 'D']
df_m = pandas.merge(df1, df2,
how='outer', on=['A'])
df_m = pandas.merge(df_m, df.loc[len(df_old)-1:, ],
how='outer', on=['A', 'B', 'D', 'F'])
最佳答案
检查 combine_first
df_old.set_index('A',inplace=True)
df1.set_index('A',inplace=True)
yourdf=df_old.combine_first(df1)
yourdf.reset_index(inplace=True)
yourdf.update(df1[['C']])
yourdf
Out[80]:
B C D E F
A
1 b1 c d1 e1 NaN
2 b2 c2 d2 e2 f2
3 b3 c d3 e3 NaN
4 b4 c1 d4 NaN f4
5 b5 c2 d5 NaN f5
关于python - 将两个时间表与一些省略的数据合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54928533/