subtruction of columns in pandas - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: subtruction of columns in pandas (/thread-10066.html) |
subtruction of columns in pandas - garikhgh0 - May-11-2018 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_2but 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 RE: subtruction of columns in pandas - scidam - May-12-2018 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] RE: subtruction of columns in pandas - garikhgh0 - May-14-2018 Thanks a lot. RE: subtruction of columns in pandas - volcano63 - May-14-2018 How about sum(df[next_col] - df[curr_col] for curr_col, next_col in zip(df.columns, df.columns[1:])) |