我有如下数据:
Currency Average Cost for two
0 Botswana Pula(P) 1100
1 Botswana Pula(P) 1200
2 Botswana Pula(P) 4000
3 Botswana Pula(P) 1500
4 Botswana Pula(P) 1500
我想创建一个新列,将成本转换为美元。仅需提及,就有12种货币。
这是我写的:
for i in range(len(df)) :
if(df[i]['Currency'] == 'Botswana Pula(P)'):
df[i]['new cost'] = df[i]['Average Cost for two'] * 0.095
if (df[i][['Currency'] == 'Brazilian Real(R$)']):
df[i]['new cost'] = df[i]['Average Cost for two'] * 0.266
and so on...
使用此代码,我遇到了一个错误。
答案 0 :(得分:2)
为所有货币创建字典,在map
列中输入其值,并在Average Cost for two
列中添加倍数:
d = {'Botswana Pula(P)':0.095, 'Brazilian Real(R$)':0.266, ...}
df['new cost'] = df['Average Cost for two'] * df['Currency'].map(d)