首页 > 解决方案 > 使用第一列作为索引合并 2 个数据框

问题描述

df 1:
   Condition   Currency   Total Hours   
0    Used        USD          100
1    Used        USD           75
2    Used        USD           13
3    Used        USD          NaN

df 2:
    Condition   Currency   Total Hours   
1    Used        USD           99
3    New         USD         1000

Desired Result:
   Condition   Currency   Total Hours   
0    Used        USD          100
1    Used        USD           99
2    Used        USD           13
3     New        USD         1000

如何使用第一列作为索引(索引)合并两个数据帧,并用 df2 的值覆盖 df1 的值?

我尝试了各种变体,但似乎没有任何效果。我试过的几个例子:

pd.merge(df, df1) = result is an empty dataframe
df.combine_first(df1) = the result is a dataframe but with the same values as df1

标签: python-3.xpandasdataframe

解决方案


尝试update

df.update(df2)
print(df)

输出:

  Condition Currency  Total Hours
0      Used      USD        100.0
1      Used      USD         99.0
2      Used      USD         13.0
3       New      USD       1000.0

推荐阅读