sum column above/below current row in pandas

Viewed 532

I'm trying to achieve this in pandas:

df['X'] = df['C'].where(row is <= current row).sum()
df['Y'] = df['C'].where(row is >= current row).sum()

What is the right syntax to make pandas sum the data from column C that are above or equal to the current row?

2 Answers

This is cumsum:

df['X'] = df['C'].cumsum()
df['Y'] = df['C'].sum() + df['C'] - df['X']
# or 
# df['Y'] = df.iloc[::-1].cumsum()

Let us try with expanding you can chose the agg function you need etc, mean/std

df['X'] = df['C'].expanding().sum()
df['Y'] = df['C'].iloc[::-1].expanding().sum()
Related