schoon
schoon

Reputation: 3324

How print col1, col2 and their difference in pandas?

I want to print col1, col2, col1 - col2 from a df.

import pandas as pd
inp = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}]
df = pd.DataFrame(inp)
print (df['c1'], df['c2'],df['c1']-df['c2'])

gives

0    10
1    11
2    12
Name: c1, dtype: int64 0    100
1    110
2    120
Name: c2, dtype: int64 0    -90
1    -99
2   -108
dtype: int64

I want

col1 col2 diff    
10 100 -90
11 110 -99
12 120 -108

Seems easy, but I cannot figure it out.

Upvotes: 0

Views: 1005

Answers (3)

shammery
shammery

Reputation: 1072

df['diff'] = df['c1'] - df['c2']
df.head()

Upvotes: 1

ansev
ansev

Reputation: 30920

Use DataFrame.assign with Series.sub this give you more flexibility

new_df = df.assign(diff = df['c1'].sub(df['c2']))
print(new_df)
   c1   c2   diff
0  10  100    -90
1  11  110    -99
2  12  120   -108

Upvotes: 0

furas
furas

Reputation: 142661

First create column with new values

 df["diff"] = df['c1']-df['c2']

and later print it

 print(df) 

or (if you have more columns and you want to skip them)

print( df[ ["c1", "c2", "diff"] ] ) 

import pandas as pd

inp = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}]

df = pd.DataFrame(inp)
df["diff"] = df['c1']-df['c2']

print(df)

print( df[ ["c1", "c2", "diff"] ] ) 

Upvotes: 2

Related Questions