Look For Patterns In A Column Of Pandas Dataframe Based On The Value Of Other Column
I have the following dataframe : in each row where key==1, I would like to search s_w column for two occurrences of 1 before and after that row( where key==1) then sum value of v
Solution 1:
I think here is necessary add mask only by Series.where
added to previous answer:
g = df[df['s_w'].eq(1)].groupby(['p','l'])['v']
df['c_s'] = g.shift(-1).add(g.shift(-2)).add(g.shift(2)).add(g.shift(1)).where(df['key'].eq(1))
print (df)
p l w s_w key v c_s
0 1 1 1 1 1 2 NaN
1 1 1 2 1 1 2 NaN
2 1 1 3 0 0 5 NaN
3 1 1 4 0 0 3 NaN
4 1 1 5 0 0 4 NaN
5 1 1 6 1 1 5 10.0 <- 2 + 2 + 5 + 1
6 1 1 7 1 0 5 NaN
7 1 1 8 1 1 1 19.0 <- 5 + 5 + 5 + 4
8 1 1 9 0 0 2 NaN
9 1 1 10 0 0 3 NaN
10 1 1 11 0 0 4 NaN
11 1 1 12 1 0 5 NaN
12 1 1 12 1 1 4 NaN
Post a Comment for "Look For Patterns In A Column Of Pandas Dataframe Based On The Value Of Other Column"