基于两个条件的Python pandas数据框回填 [英] Python pandas dataframe backfill based on two conditions

查看:93
本文介绍了基于两个条件的Python pandas数据框回填的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据框:

I have a dataframe like this:

   Bool   Hour
0  False  12
1  False  24
2  False  12
3  False  24
4  True   12
5  False  24
6  False  12
7  False  24
8  False  12
9  False  24
10 False  12
11 True   24

,我想回填布尔"(Bool)列中的True值,直到小时"(Hour)首次达到"12".结果将是这样的:

and I would like to backfill the True value in 'Bool' column to the point when 'Hour' first reaches '12'. The result would be something like this:

   Bool   Hour  Result
0  False  12    False
1  False  24    False
2  False  12    True      <- desired backfill
3  False  24    True      <- desired backfill
4  True   12    True
5  False  24    False
6  False  12    False
7  False  24    False
8  False  12    False
9  False  24    False
10 False  12    True      <- desired backfill
11 True   24    True

任何帮助将不胜感激!非常感谢你!

Any help is greatly appreciated! Thank you very much!

推荐答案

这很难实现,在这里我们可以将 groupby idxmax

This is a little bit hard to achieve , here we can use groupby with idxmax

s=(~df.Bool&df.Hour.eq(12)).iloc[::-1].groupby(df.Bool.iloc[::-1].cumsum()).transform('idxmax')
df['result']=df.index>=s.iloc[::-1]
df
Out[375]: 
     Bool  Hour  result
0   False    12   False
1   False    24   False
2   False    12    True
3   False    24    True
4    True    12    True
5   False    24   False
6   False    12   False
7   False    24   False
8   False    12   False
9   False    24   False
10  False    12    True
11   True    24    True

这篇关于基于两个条件的Python pandas数据框回填的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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