pandas:基于相同ID的数据来自另一个数据框的数据的fillna [英] pandas: fillna with data from another dataframe, based on the same ID

查看:45
本文介绍了pandas:基于相同ID的数据来自另一个数据框的数据的fillna的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

df1 缺少值:

df1=

    ID age 
    1  12 
    2  na
    3  23
    4  na
    5  na
    6  na 

,我还有另一个 df

df2=

    ID age
    2   4
    4   5
    5   6 
    6   7

我要<$ c $的 fillna c> df1 ,使用 df2 ,基于相同的 ID

I want to fillna of df1, using df2, based on same ID:

df1 (after fillna)=

    ID age 
    1  12 
    2  4
    3  23
    4  5
    5  6
    6  7


推荐答案

您可以将 ID 设置为两个数据帧的索引,然后使用 fillna()方法,该方法填充缺失值,同时匹配两个数据框的索引:

You can set ID as index for both dataframes, and then use the fillna() method, which fill missing values, while matching the index of the two dataframes:

df1.set_index("ID").age.fillna(df2.set_index("ID").age).reset_index()

#  ID   age
#0  1   12
#1  2   4
#2  3   23
#3  4   5
#4  5   6
#5  6   7




另一个选择是 combine_first 从第一个数据框中获取值,如果不是 null ,则从第二个数据框中获取具有索引和匹配的列的值:


Another option is, combine_first, which takes values from the first dataframe, if not null, otherwise takes values from the second dataframe with index and columns matched:

df1.set_index("ID").combine_first(df2.set_index("ID")).reset_index()

#  ID   age
#0  1   12.0
#1  2   4.0
#2  3   23.0
#3  4   5.0
#4  5   6.0
#5  6   7.0

这篇关于pandas:基于相同ID的数据来自另一个数据框的数据的fillna的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆