revendar
revendar

Reputation: 391

Pandas rolling get last true value

I have a dataframe like below.

import pandas as pd
d = {'col1': ['a', 'b', 'c', 'd', 'e', 'f'], 'col2': [False, False, True, False, True, False]}
df = pd.DataFrame(data=d)
print df

   col1   col2
0     a  False
1     b  False
2     c   True
3     d  False
4     e   True
5     f  False

I would like to implement a rolling window of say 3 on col3 and find the last True value and return col1 value for that row. If true value is not found it would take the first element of rolling col1. The below data has a shifted output on col3.

Expected output:

   col1   col2   col3
0     a  False   a
1     b  False   a
2     c   True   a
3     d  False   c
4     e   True   c
5     f  False   e

Upvotes: 0

Views: 1892

Answers (1)

cs95
cs95

Reputation: 403278

You may not need a rolling window here. Let's try where/mask + ffill:

df['col3'] = df['col1'].where(df['col2']).shift().ffill().fillna(df.at[0, 'col1'])    
df

  col1   col2 col3
0    a  False    a
1    b  False    a
2    c   True    a
3    d  False    c
4    e   True    c
5    f  False    e

Upvotes: 2

Related Questions