如果每个组仅使用一个非NaN的值
ffill(前向填充)和
bfill每组(向后填充),所以需要
apply有
lambda:
df['three'] = df.groupby(['one','two'], sort=False)['three'] .apply(lambda x: x.ffill().bfill())print (df) one two three0 1 1 10.01 1 1 10.02 1 1 10.03 1 2 20.04 1 2 20.05 1 2 20.06 1 3 NaN7 1 3 NaN
但是,如果每个组有多个值,并且需要用
NaN某个常量替换-例如
mean按组:
print (df) one two three0 1 1 10.01 1 1 40.02 1 1 NaN3 1 2 NaN4 1 2 20.05 1 2 NaN6 1 3 NaN7 1 3 NaNdf['three'] = df.groupby(['one','two'], sort=False)['three'] .apply(lambda x: x.fillna(x.mean()))print (df) one two three0 1 1 10.01 1 1 40.02 1 1 25.03 1 2 20.04 1 2 20.05 1 2 20.06 1 3 NaN7 1 3 NaN
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)