python - Pandas:如何将字典映射到 2 列?

标签 python pandas dataframe dictionary

我有以下字典:

rates = {'USD': 
              {'2019': 1,
               '2020': 2,
               '2021': 3},
         'CAD':
              {'2019': 4,
               '2020': 5,
               '2021': 6}
         }
我有以下虚拟数据框:
   Item Currency Year Rate
0  1    USD      2019 
1  2    USD      2020
2  3    CAD      2021
3  4    CAD      2019
4  5    GBP      2020
我现在想填充列 Rate通过映射正确率,其中rate = f(currency,year) .我正在尝试:
def map_rate(data, rates):

    for index, row in data.iterrows():

        currency = str(row['Currency'])

        if currency in list(rates.keys()):

            year = str(row['Year'])
            rate = rates[currency][year]

        else:
            rate = 1

    return rate
我像下面这样使用上面的:
df['Rate'] = map_rate(test, rates)
但是,这仅返回第一流,例如值 1,而不是适当的费率:
    Item Currency Year  Rate
0   1    USD      2019  1
1   2    USD      2020  1
2   3    CAD      2021  1
3   4    CAD      2019  1
4   5    GBP      2020  1
预期的结果是:
    Item Currency Year  Rate
0   1    USD      2019  1
1   2    USD      2020  2
2   3    CAD      2021  6
3   4    CAD      2019  4
4   5    GBP      2020  1
我的错误在哪里?

最佳答案

使用 .apply 例如:

df['Rate'] = df.apply(lambda x: rates[x['Currency']][x['Year']], axis=1)
# OR
df['Rate'] = df.apply(lambda x: rates.get(x['Currency'], dict()).get(x['Year'], 1), axis=1)
print(df)
输出:
  Item Currency  Year  Rate
0    1      USD  2019     1
1    2      USD  2020     2
2    3      CAD  2021     6
3    4      CAD  2019     4
4    5      GBP  2020     1

关于python - Pandas:如何将字典映射到 2 列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67989170/

相关文章:

python - 如何用数据框中的所有行名称标记轴

IO绑定(bind)任务中的Python多线程

python - 使用 Pandas 将 groupby.sum() 的结果映射到另一个数据帧?

python - 如何在 iPad 上使用 Python 就像在 PC 上工作一样?

python - 将数据框列与系列进行比较

python - 分组行 python pandas

python - 基于 Pandas 组内日期的有效转换?

python - Dataframe 大型 JSON(嵌套的嵌套)

python - 将每个批处理或纪元的验证准确性打印到控制台(Keras)

python - Pandas :返回 NaN 行