bobby666
bobby666

Reputation: 67

How to find the difference between two columns in a dataframe with either rows in the column have -ve and/or +ve values in Python

I have two columns (x & y) in a df with 4 row scenarios (+ve)-(+ve), (-ve)-(-ve), (+ve)-(-ve) and (-ve)-(+ve).

df

 x    y
 3    2
-4   -2
 2   -1
-6    1

I want to insert a third column z in the same df and the end result as shown below

df

 x    y    z
 3    2    1
-4   -2   -2
 2   -1    3
-6    1   -5

Upvotes: 0

Views: 62

Answers (2)

Mehul Gupta
Mehul Gupta

Reputation: 1939

x['z']=x.apply(lambda row: row[0]-row[1],axis=1)

enter image description here

passing axis=1 to apply() helps us to access all values of a row.

Upvotes: 0

Vijay Lingam
Vijay Lingam

Reputation: 101

Are you looking for this?

df['z'] = df['x'] - df['y']

Upvotes: 2

Related Questions