使用键将以前的非缺失值填充到丢失的 pandas 数据中 [英] Fill in missing pandas data with previous non-missing value, grouped by key
本文介绍了使用键将以前的非缺失值填充到丢失的 pandas 数据中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在处理像这样的pandas DataFrames:
I am dealing with pandas DataFrames like this:
id x
0 1 10
1 1 20
2 2 100
3 2 200
4 1 NaN
5 2 NaN
6 1 300
7 1 NaN
我想用具有相同'id'值的行中的每个NAN'x'替换为先前的非NAN'x':
I would like to replace each NAN 'x' with the previous non-NAN 'x' from a row with the same 'id' value:
id x
0 1 10
1 1 20
2 2 100
3 2 200
4 1 20
5 2 200
6 1 300
7 1 300
是否有一些巧妙的方法可以执行此操作而无需手动循环遍历行?
Is there some slick way to do this without manually looping over rows?
推荐答案
您可以执行 groupby/forward-fill 操作:
import numpy as np
import pandas as pd
df = pd.DataFrame({'id': [1,1,2,2,1,2,1,1], 'x':[10,20,100,200,np.nan,np.nan,300,np.nan]})
df['x'] = df.groupby(['id'])['x'].ffill()
print(df)
收益
id x
0 1 10.0
1 1 20.0
2 2 100.0
3 2 200.0
4 1 20.0
5 2 200.0
6 1 300.0
7 1 300.0
这篇关于使用键将以前的非缺失值填充到丢失的 pandas 数据中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文