Python Forum

Full Version: subtruction of columns in pandas
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I friends. I would like to ask how to orgnize subtruction of columns. so the dataframe is as below:

when I subtruct columns from each other I use the following code:

df['new'] = df.column_1 - df.column_2
but I need to subtract b from a, c from b and so on and combine(plus) the results in one column
df = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 5)),columns=['a', 'b', 'c', 'd', 'e'])
thanks in advance

a b c d e
6 5 6 8 3 
4 9 2 4 2 
1 7 9 4 3 
3 1 5 2 3 
2 8 3 5 7 
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 5)),columns=['a', 'b', 'c', 'd', 'e'])
df['new'] = 0.0
for i in range(df.shape[-1] - 1):
    df['new'] += df.iloc[:, i] -  df.iloc[:, i + 1]
Thanks a lot.
How about

sum(df[next_col] - df[curr_col] for curr_col, next_col in zip(df.columns, df.columns[1:]))