Python:将一个数据帧中的值添加到另一个数据帧(具有多个条件)

标签 python pandas dataframe row multiple-columns

我有两个数据框df1df2看起来像这样:

示例:

x1 = [{'partner': "Afghanistan", 'trade_value':100, 'commodity': 1}, 
      {'partner':"Zambia",'trade_value':110, 'commodity': 2}, 
      {'partner': "Germany",'trade_value':120, 'commodity': 2},
      {'partner': "Afghanistan",'trade_value':150, 'commodity': 2},
      {'partner': "USA",'trade_value':1120, 'commodity': 5}];

df1 = pd.DataFrame(x1)

x2 = [{'country': "Afghanistan", 'commodity': 5, 'tariff': 3.5},
      {'country': "Afghanistan", 'commodity': 3, 'tariff': 6.2},
      {'country': "Afghanistan", 'commodity': 1, 'tariff': 9.9},
      {'country': "Afghanistan", 'commodity': 2, 'tariff': 1.4},
      {'country': "USA", 'commodity': 5, 'tariff': 4.3},
      {'country': "Germany", 'commodity': 7, 'tariff': 6.5},
      {'country': "Germany", 'commodity': 2, 'tariff': 8.8}];

df2 = pd.DataFrame(x2)

我想向 df1 添加新列称为“关税”并分配df1中的每个“合作伙伴”和“商品”其适当的“关税”来自df2 .

注意:有时是 df1 中的“伙伴”国家由于多次交易而重复。此外,并非所有关税都可在 df2 中找到。所以我不介意在 df1 中留下一个单元格空。

到目前为止我处于这个阶段:

#Add new column
df1['tariff'] = 0;

for index, row in df1.iterrows():
    for index, row2 in df2.iterrows():
        if row['partner'] == row2['country']:
            if row['commodity'] == row2['commodity']
                #Dont know what to put here

如果我使用df1['tariff'].replace(row['tariff'],row2['tariff'],inplace=True);我得到的所有关税栏都填写了关税 9.9

df1 的输出应如下所示:

|  partner   | trade_value | commodity | tariff |
|------------|-------------|-----------|--------|
| Afghanistan|     100     |     1     |   9.9  |
| Zambia     |     110     |     2     |   NaN  |
| Germany    |     120     |     2     |   8.8  |
| Afghanistan|     150     |     2     |   1.4  |
| USA        |     1120    |     5     |   4.3  |

最佳答案

合并

您可以简单地使用 merge连接重叠列上的两个数据框:

pd.merge(left=df1, right=df2, how='left', left_on=['partner', 'commodity'],
         right_on = ['country', 'commodity']).drop(['country'], axis = 1)

     commodity      partner  trade_value  tariff
0          1  Afghanistan          100     9.9
1          2       Zambia          110     NaN
2          2      Germany          120     8.8
3          2  Afghanistan          150     1.4
4          5          USA         1120     4.3

关于Python:将一个数据帧中的值添加到另一个数据帧(具有多个条件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53449608/

相关文章:

r - 如何在R中制作排名列

python - Pandas Dataframe 特殊计数

python - 在 Python 中读取 UDP 数据包的缓冲区大小

python - 根据另一个 csv 文件过滤 csv 文件中的行并将过滤后的数据保存在新文件中

python - 替换 pandas 数据框中的字符串

dataframe - 获取子集化后剩余的数据帧

python - 给定一个字符串列表,如何使用正则表达式找到第一个字符串匹配子字符串的位置?

python - Django模型保存self.field.rel.to.DoesNotExist

python - 如何在 Flask SQLAlchemy 中使用 SUM 聚合函数?

python - 如何将数值与 nan 值分开?