从不同的DataFrame中减去两列

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

Subtract two columns from different DataFrame

问题

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

我尝试了以下代码:

A_minus_B = dfA['Country'] - dfB['Country']

类型错误str和str不能相减

我的期望是:

dfA Country
1. United States
2. Puerto Rico
3. Colombia

dfB Country
1. Puerto Rico
2. Argentina
3. Canada

A_minus_B Country
1. United States
2. Colombia
3. Argentina
英文:

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

I'm trying the following code:

A_minus_B = dfA['Country'] - dfB['Country']

Typerror: - with str & str

What I'm expecting is:

dfA Country
1. United States
2. Puerto Rico
3. Colombia

dfB Country
1. Puerto Rico
2. Argentina
3. Canada

A_minusB Country
1. United States
2. Colombia
3. Argentina

答案1

得分: 2

pd.concat([dfA, dfB]).drop_duplicates(keep=False, ignore_index=True)
使用 `pd.concat`:

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

         Country
0  United States
1       Colombia
2      Argentina
3         Canada

<details>
<summary>英文:</summary>

Use `pd.concat`:

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

     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

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:

确定