【问题标题】:How to iterate over rows in Pandas Dataframe [duplicate]如何遍历 Pandas Dataframe 中的行 [重复]
【发布时间】:2019-07-19 16:03:34
【问题描述】:

我的数据如下所示:

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

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

【问题讨论】:

    标签: python pandas dataframe iteration


    【解决方案1】:

    为所有货币创建字典,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) 
    

    【讨论】:

      猜你喜欢
      • 2022-10-25
      • 2012-05-30
      • 2018-12-28
      相关资源
      最近更新 更多