Skip to content
Advertisement

How to apply function vertically in df

I want to add column values vertically from top to down

def add(x,y):
    return x,y

df = pd.DataFrame({'A':[1,2,3,4,5]})

df['add'] = df.apply(lambda row : add(row['A'], axis = 1)

I tried using apply but its not working

Desired output is basically adding A column values 1+2, 2+3:

   A   add
0  1    1
1  2    3
2  3    5
3  4    7
4  5    9

Advertisement

Answer

You can apply rolling.sum on a moving window of size 2:

df.A.rolling(2, min_periods=1).sum()

0    1.0
1    3.0
2    5.0
3    7.0
4    9.0
Name: A, dtype: float64

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement