Python Forum
subtruction of columns in pandas
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
subtruction of columns in pandas
#1
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 
Reply
#2
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]
Reply
#3
Thanks a lot.
Reply
#4
How about

sum(df[next_col] - df[curr_col] for curr_col, next_col in zip(df.columns, df.columns[1:]))
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  iretate over columns in df and calculate euclidean distance with one column in pandas Pit292 0 3,266 May-09-2021, 06:46 PM
Last Post: Pit292
  pandas.to_datetime: Combine data from 2 columns ju21878436312 1 2,417 Feb-20-2021, 08:25 PM
Last Post: perfringo
  Remove extra count columns created by pandas groupby spyf8 1 2,685 Feb-10-2021, 09:19 AM
Last Post: Naheed
  Pandas: summing columns conditional on the column labels ddd2332 0 2,074 Sep-10-2020, 05:58 PM
Last Post: ddd2332
  Difference of two columns in Pandas dataframe zinho 2 3,312 Jun-17-2020, 03:36 PM
Last Post: zinho
  Pandas dataframe columns collapsed in Spyder when printing UniKlixX 2 4,656 Nov-04-2019, 07:00 AM
Last Post: UniKlixX
  [pandas] How to re-arrange DataFrame columns SriMekala 8 4,850 Jun-22-2019, 12:55 AM
Last Post: scidam
  Pandas - cumulative sum of two columns tobbs 12 8,650 May-25-2019, 08:37 PM
Last Post: tobbs
  comparing two columns two different files in pandas nuncio 0 2,370 Jun-06-2018, 01:04 PM
Last Post: nuncio

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020