python 中货币的 if / then 语句

if / then statement for currency in python

正在尝试使用 python 在 df 中转换货币。 我有两列:价格和货币。 我尝试使用 if/elif/else 语句,但我做错了。

Sample of df: 
|price|currency|boat type| year built|
|-----|--------|---------|-----------|
|3490 |EUR     |console  | 2020      |
|2299 |EUR     |fishing  | 2019      |
|3500 |CHF     |fishing  | 1987      |
|4600 |£      |runabout | 2020      |

如有任何建议,我们将不胜感激。谢谢

我试过的代码...

if drop_boats['Currency'] == 'EUR':
    drop_boats['Price'] = drop_boats['Price'] * 1.10 
elif drop_boats['Currency'] == 'CHF':
    drop_boats['Price'] = drop_boats['Price'] * 1.08 
elif drop_boats['Currency'] == 'DKK':
    drop_boats['Price'] = drop_boats['Price'] * 0.15 
elif drop_boats['Currency'] == '£':
    drop_boats['Price'] = drop_boats['Price'] * 1.32
else:
     drop_boats['Price' ]= drop_boats['Price']

我收到此错误:ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

您可能需要 loc 布尔索引。如果没有显示示例输入和输出数据,请。

drop_boats.loc[drop_boats['Currency'].eq('EUR'), 'Price'] *= 1.10

您可以使用 iter.rows() 遍历 pandas 行并进行计算。参考以下代码:

for index, row in df.iterrows():
    if row['Currency'] == 'EUR':
        row['Price'] = row['Price'] * 1.10 
    elif row['Currency'] == 'CHF':
        row['Price'] = row['Price'] * 1.08 
    elif row['Currency'] == 'DKK':
        row['Price'] = row['Price'] * 0.15 
    elif row['Currency'] == '£':
        row['Price'] = row['Price'] * 1.32
    else:
        row['Price' ]= row['Price']

一种实现您想要的方法是这样的:

for index, row in drop_boats.iterrows():
  if row['Currency'] == 'EUR':
    drop_boats.loc[index, 'Price'] = row['Price'] * 1.10

您可以相应地添加您的其他条件...