gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:25:49 27 4
gpt4 key购买 nike

我有缺失值的数据框 (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)

临时结果:

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

然后我需要遍历所有值,所以我正在寻找更有效的方法。

有什么建议吗?

最佳答案

如果 "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

关于python - 根据其他数据框 Python 估算 NaN 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55888604/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com