Skip to content Skip to sidebar Skip to footer

Calculate A Value In A Row Based On Before And After Rows In Pandas

I have the following dataframe: p l w s_w v 1 1 1 1 2 1 1 2 1 2 1 1 3 0 5 1 1 4 1 5 1 1 5 1 5 2 1 1 1 1 2 1 2 0 2 2 1 3 0 3 2 1 4 0 4 2 1 5

Solution 1:

Idea is filtered rows with 1 and use rolling sum with shift values for correct align:

s = df.loc[df['s_w'].eq(1), 'v']

df['c_s'] = s.rolling(2).sum().shift().add(s.iloc[::-1].rolling(2).sum().shift())
print (df)
    p  l  w  s_w  v   c_s
0   1  1  1    1  2   NaN
1   1  1  2    1  2   NaN
2   1  1  3    0  5   NaN
3   1  1  4    1  5  10.0
4   1  1  5    1  5  13.0
5   2  1  1    1  1  19.0
6   2  1  2    0  2   NaN
7   2  1  3    0  3   NaN
8   2  1  4    0  4   NaN
9   2  1  5    1  5   NaN
10  2  1  6    1  4   NaN

Another idea:

df['c_s'] = s.shift(-1).add(s.shift(-2)).add(s.shift(2)).add(s.shift(1))

EDIT:

Solution per groups:

s = df[df['s_w'].eq(1)]

f = lambda x: x.rolling(2).sum().shift()
df['c_s'] = s.groupby(['p','l'])['v'].apply(f).add(s.iloc[::-1].groupby(['p','l'])['v'].apply(f))

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))

Post a Comment for "Calculate A Value In A Row Based On Before And After Rows In Pandas"