I have a large df of purchases, sorted by person and datetime. I want to shorten the df to rows where a fruit is purchased and up to 5 rows before that fruit purchase for each person. If one of the 5 rows is a fruit purchase, then I only need to extract the rows above till that last fruit purchase.
fruits = ["apple", "banana", "pear"]
date pesron item
10:00 amy apple
10:01 amy pear
10:02 amy ipad (6 rows above 10:08 banana purchase, so delete)
10:03 amy headphones
10:04 amy missing
10:05 amy laptop
10:06 amy unknown
10:07 amy table
10:08 amy banana (one of the 5 rows above 10:10 banana purchase is also a fruit so stop here)
10:09 amy unknown
10:10 amy banana
... ben
Expected Output
10:00 amy apple
10:01 amy pear
10:03 amy headphones
10:04 amy missing
10:05 amy laptop
10:06 amy unknown
10:07 amy table
10:08 amy banana
10:09 amy unknown
10:10 amy banana
I tried
m1= df.item.isin(fruits)
df.loc[m1, df.iloc[idx-5,:]]