How to iterate over rows in Pandas Dataframe
本问题已经有最佳答案,请猛点这里访问。
我有这样的数据:
1 2 3 4 5 6 | 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种货币。
这就是我写的:
1 2 3 4 5 6 | 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 2 3 | d = {'Botswana Pula(P)':0.095, 'Brazilian Real(R$)':0.266, ...} df['new cost'] = df['Average Cost for two'] * df['Currency'].map(d) |