根据另一列中的条件填充 pandas [英] pandas ffill based on condition in another column
本文介绍了根据另一列中的条件填充 pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Pandas DataFrame,如下所示.
I have a pandas DataFrame as shown below.
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]
})
除了要每个值也对应于相应的 category
,我想使用 ffill
来填充 rate
的值.怎样使 df
看起来像这样?:
I want to use ffill
to forward fill the values of rate
, except that I want each value to correspond also to the appropriate category
. How can I get df
to look like this?:
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的列,则可以使用它在费率列中填充NaN:
If you have other columns with NaN that you don't want fill, then you can use this to just ffill NaN in rate column:
df['rate'] = df.groupby('category')['rate'].ffill()
这篇关于根据另一列中的条件填充 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文