根据相似列的值填写一列中的NA值 [英] Fill the NA value in one column according to values of similar columns

查看:64
本文介绍了根据相似列的值填写一列中的NA值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在给定的值中填充nan的值如下:

I want to fill the value of the nan in the given value as following:

df = pd.DataFrame({'A' : ['aa', 'bb', 'cc', 'aa'], 
                   'B': ['xx', 'yy', 'zz','xx'], 
                   'C': ['2', '3','8', np.nan]})
print (df)

A  B  C
aa xx 2
bb yy 3
cc zz 8
aa xx NaN  

预期输出:

A  B  C
aa xx 2
bb yy 3
cc zz 8
aa xx 2

由于 A 列和 B 列在第三列中的值为 2,因此最后一行在 C 列中也应为 2.

Since column A and B have value 2 in the third column, therefore last row should also have 2 in the C column.

推荐答案

使用 GroupBy.ffillDataFrame.sort_valuesDataFrame.sort_index 用于 NaN 到组结束:

df['C'] = df.sort_values(['A','B','C']).groupby(['A','B'])['C'].ffill().sort_index()
print (df)
    A   B  C
0  aa  xx  2
1  bb  yy  3
2  cc  zz  8
3  aa  xx  2

另一种每组向前和向后填充的解决方案:

Another solution with forward and back filling per groups:

df['C'] = df.groupby(['A','B'])['C'].apply(lambda x: x.ffill().bfill())

这篇关于根据相似列的值填写一列中的NA值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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