如何遍历Pandas Dataframe中的行

时间:2019-02-26 06:58:22

标签: python pandas dataframe iteration

我有如下数据:

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...

使用此代码,我遇到了一个错误。

1 个答案:

答案 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) 
相关问题