从不同的DataFrame中减去两列

huangapple go评论104阅读模式
英文:

Subtract two columns from different DataFrame

问题

我想从DataFrame dfACountry列中减去DataFrame dfB中的Country列。

我尝试了以下代码:

  1. A_minus_B = dfA['Country'] - dfB['Country']
  2. 类型错误strstr不能相减

我的期望是:

  1. dfA Country
  2. 1. United States
  3. 2. Puerto Rico
  4. 3. Colombia
  5. dfB Country
  6. 1. Puerto Rico
  7. 2. Argentina
  8. 3. Canada
  9. A_minus_B Country
  10. 1. United States
  11. 2. Colombia
  12. 3. Argentina
英文:

I want to subtract column Country from DataFrame dfA with column Country in DataFrame dfB.

I'm trying the following code:

  1. A_minus_B = dfA['Country'] - dfB['Country']
  2. Typerror: - with str & str

What I'm expecting is:

  1. dfA Country
  2. 1. United States
  3. 2. Puerto Rico
  4. 3. Colombia
  5. dfB Country
  6. 1. Puerto Rico
  7. 2. Argentina
  8. 3. Canada
  9. A_minusB Country
  10. 1. United States
  11. 2. Colombia
  12. 3. Argentina

答案1

得分: 2

  1. pd.concat([dfA, dfB]).drop_duplicates(keep=False, ignore_index=True)
  1. 使用 `pd.concat`
  2. ```python
  3. pd.concat([dfA, dfB]).drop_duplicates(keep=False, ignore_index=True)
  4. Country
  5. 0 United States
  6. 1 Colombia
  7. 2 Argentina
  8. 3 Canada
  1. <details>
  2. <summary>英文:</summary>
  3. Use `pd.concat`:

>>> pd.concat([dfA, dfB]).drop_duplicates(keep=False, ignore_index=True)

  1. Country

0 United States
1 Colombia
2 Argentina
3 Canada

答案2

得分: 1

A_minus_B = dfA.loc[~dfA['Country'].isin(dfB['Country']), 'Country']

英文:

You can use the below

  1. A_minus_B = dfA.loc[~dfA[&#39;Country&#39;].isin(dfB[&#39;Country&#39;]), &#39;Country&#39;]

答案3

得分: 0

你想创建 dfC = dfA.merge(dfB, "Country")

将所有内容合并到一个数据框中,然后你就可以很好地执行减法。


你忽略了在你的问题中提供一个可复现的示例。一旦你解决了技术细节,描述解决方案和你得到的结果。

英文:

You want to create dfC = dfA.merge(dfB, &quot;Country&quot;).

With everything in a single dataframe, then you will then be
in a good position to perform the subtraction.


You neglected to put a reproducible example in your question.
Once you work out the technical details,
describe
the solution and the results that you obtain.

huangapple
  • 本文由 发表于 2023年2月19日 02:54:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75495660.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定