如何对 pandas 中的每个组进行前填 [英] How to do forward filling for each group in pandas

查看:90
本文介绍了如何对 pandas 中的每个组进行前填的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与下面类似的数据框

I have a dataframe similar to below

id A   B   C   D E
1  2   3   4   5 5
1  NaN 4   NaN 6 7
2  3   4   5   6 6
2  NaN NaN 5   4 1

我想对前向填充中的每个组的ABC列进行空值插补.这就是说,我希望在每个id上应用正向填充.我该怎么办?

I want to do a null value imputation for columns A, B, C in a forward filling but for each group. That means, I want the forward filling be applied on each id. How can I do that?

推荐答案

使用 fillna 并最后转换为整数:

Use GroupBy.ffill for forward filling per groups for all columns, but if first values per groups are NaNs there is no replace, so is possible use fillna and last casting to integers:

print (df)
   id    A    B    C  D    E
0   1  2.0  3.0  4.0  5  NaN
1   1  NaN  4.0  NaN  6  NaN
2   2  3.0  4.0  5.0  6  6.0
3   2  NaN  NaN  5.0  4  1.0

cols = ['A','B','C']
df[['id'] + cols] = df.groupby('id')[cols].ffill().fillna(0).astype(int)
print (df)
   id  A  B  C  D    E
0   1  2  3  4  5  NaN
1   1  2  4  4  6  NaN
2   2  3  4  5  6  6.0
3   2  3  4  5  4  1.0

详细信息:

print (df.groupby('id')[cols].ffill().fillna(0).astype(int))
   id  A  B  C
0   1  2  3  4
1   1  2  4  4
2   2  3  4  5
3   2  3  4  5

或者:

cols = ['A','B','C']
df.update(df.groupby('id')[cols].ffill().fillna(0))
print (df)
   id    A    B    C  D    E
0   1  2.0  3.0  4.0  5  NaN
1   1  2.0  4.0  4.0  6  NaN
2   2  3.0  4.0  5.0  6  6.0
3   2  3.0  4.0  5.0  4  1.0

这篇关于如何对 pandas 中的每个组进行前填的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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