【问题标题】:How can I fill the data frame NA value using data in another dataframe (Python) [duplicate]如何使用另一个数据帧(Python)中的数据填充数据帧NA值[重复]
【发布时间】:2018-10-12 07:47:07
【问题描述】:

我在 Python 中有两个数据框,如何使用 df2 的值填充 df1 中的 NAN 值?我想要像df3 这样的决赛,如下所示。我尝试了几种方法,但都失败了。

df3 = df1.update(df2)

df3 = df1.combine_first(df2)

我找不到解决方案,有人可以帮忙吗?如何在 Python 中编写这部分代码?

如何使用 Df2 填充 DF1 中的 NAN 值:

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    combine_first 的想法是正确的,但需要先通过 set_index 对齐索引:

    import pandas as pd, numpy as np
    
    df1 = pd.DataFrame({'Group': ['A', 'A', 'A', 'B', 'B', 'B'],
                        'Key': ['AA1', 'AB2', 'AC3', 'BD4', 'BE5', 'BF6'],
                        'Value1': [np.nan, 20, 40, 60, np.nan, np.nan],
                        'Value2': [np.nan, 30, 50, 23, np.nan, np.nan]})
    
    df2 = pd.DataFrame({'Key': ['AA1', 'BE5', 'BF6'],
                        'Value1': [66, 20, 21],
                        'Value2': [33, 60, 70]})
    
    res = df1.set_index('Key').combine_first(df2.set_index('Key')).reset_index()
    
    print(res)
    
       Key Group  Value1  Value2
    0  AA1     A      66      33
    1  AB2     A      20      30
    2  AC3     A      40      50
    3  BD4     B      60      23
    4  BE5     B      20      60
    5  BF6     B      21      70
    

    【讨论】:

    • 非常感谢,完美运行,为我节省了大量时间。 :)
    猜你喜欢
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 2021-07-02
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多