我有以下字典:
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/