简体   繁体   中英

Subtract columns from two data frames based on a common column

df1:

  1. Asia 34
  2. America 74
  3. Australia 92
  4. Africa 44

df2:

  1. Asia 24
  2. Australia 90
  3. Africa 30

I want the output of df1 - df2 to be

  1. Asia 10
  2. America 74
  3. Australia 2
  4. Africa 14

I am getting troubled by this, I am newbie into pandas. Please help out.

Use Series.sub with mapped second Series by Series.map :

df1['B'] = df1['B'].sub(df1['A'].map(df2.set_index('A')['B']), fill_value=0)
print (df1)
           A     B
0       Asia  10.0
1    America  74.0
2  Australia   2.0
3     Africa  14.0

If possible changed ordering of first column convert both first columns to index by DataFrame.set_index and subtract:

df2 = df1.set_index('A')['B'].sub(df2.set_index('A')['B'], fill_value=0).reset_index()
print (df2)
           A     B
0     Africa  14.0
1    America  74.0
2       Asia  10.0
3  Australia   2.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM