根据其他数据框Python估算NaN值

时间:2019-04-28 08:55:41

标签: python pandas merge

我有缺少值的数据帧(DF1),我想在保留索引而不对它们进行排序的同时,从其他数据帧(DF2)中估算那些丢失的值(非常重要)。 我正在尝试找到最有效的方法。

DF1:

index  id  test
3      45   6.9
56     2    NA
1      789  8
29     12   4.7

DF2:

index  id  test
56     2    2.3

结果:

index  id  test
3      45   6.9
56     2    2.3
1      789  8
29     12   4.7

我尝试过:

tempResult = pd.merge(DF1, DF2,on=id,how='outer',sort=False).set_index(DF1.index)

tempResult:

index  id  test_x  test_y
3      45   6.9    NA
56     2    NA     2.3
1      789  8      NA
29     12   4.7    NA

然后我需要检查所有值,以便寻找更有效的方法。

有什么建议吗?

2 个答案:

答案 0 :(得分:3)

使用combine_first()

print(df1.combine_first(df2))

        id  test
index           
1      789   8.0
3       45   6.9
29      12   4.7
56       2   2.3

答案 1 :(得分:3)

如果实际上"index"是此处的DataFrame.index,那么您应该可以使用DataFrame.fillna

df1.fillna(df2)

如果没有,那么可能首先需要使用set_index,例如:

df1.set_index('index').fillna(df2.set_index('index'))

[出]

        id  test
index           
3       45   6.9
56       2   2.3
1      789   8.0
29      12   4.7