If any of the last N (3) rows OR current were True in a groupby, then I want the output to be true.
This is how I have been trying to do it, either with transform since its a single column.
import pandas as pd
data = [
['False', 'CLE',],
['False', 'CLE'],
['True', 'CLE'],
['False', 'MON'],
['False', 'CLE'],
['False', 'CLE'],
['False', 'CLE'],
['False', 'CLE']
]
# Create the pandas DataFrame
df = pd.DataFrame(data,
columns=["bool", "city"])
df['x'] = df.groupby(['city'])['bool']
.transform(lambda x: x==True &
x.index
.isin(x.index[-2:]))
Output should be:
False
False
True
False
True
True
False
False
question from:https://stackoverflow.com/questions/66056039/pandas-checking-true-false-in-groupby-for-last-n-rows