简体   繁体   English

基于公共列从两个数据帧中减去列

[英]Subtract columns from two data frames based on a common column

df1: df1:

  1. Asia 34亚洲 34
  2. America 74美国 74
  3. Australia 92澳大利亚 92
  4. Africa 44非洲 44

df2: df2:

  1. Asia 24亚洲 24
  2. Australia 90澳大利亚 90
  3. Africa 30非洲 30

I want the output of df1 - df2 to be我希望 df1 - df2 的 output 是

  1. Asia 10亚洲 10
  2. America 74美国 74
  3. Australia 2澳大利亚 2
  4. Africa 14非洲 14

I am getting troubled by this, I am newbie into pandas.我对此感到困扰,我是 pandas 的新手。 Please help out.请帮忙。

Use Series.sub with mapped second Series by Series.map :使用Series.subSeries.map映射的第二个Series

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:如果可能,第一列的更改顺序将两个第一列转换为索引DataFrame.set_index并减去:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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