我有一个熊猫DataFrame,如下所示。
df = pd.DataFrame({
'date': ['2011-01-01', '2011-01-01', '2011-02-01', '2011-02-01', '2011-03-01', '2011-03-01', '2011-04-01', '2011-04-01'],
'category': [1, 2, 1, 2, 1, 2, 1, 2],
'rate': [0.5, 0.75, np.nan, np.nan, 1, 1.25, np.nan, np.nan]
})
我想使用ffill
前向填充的值rate
,除了我希望每个值也要对应于适当的值category
。我如何df
看起来像这样?:
df
category date rate
1 2011-01-01 0.50
2 2011-01-01 0.75
1 2011-02-01 0.50
2 2011-02-01 0.75
1 2011-03-01 1.00
2 2011-03-01 1.25
1 2011-04-01 1.00
2 2011-04-01 1.25
用途groupby
:
df.groupby('category').ffill()
输出:
category date rate
0 1 2011-01-01 0.50
1 2 2011-01-01 0.75
2 1 2011-02-01 0.50
3 2 2011-02-01 0.75
4 1 2011-03-01 1.00
5 2 2011-03-01 1.25
6 1 2011-04-01 1.00
7 2 2011-04-01 1.25
如果您还有其他不希望使用NaN填充的列,则可以使用它在rate列中填充NaN:
df['rate'] = df.groupby('category')['rate'].ffill()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句