【问题标题】:Pandas DataFrame currency conversionPandas DataFrame 货币转换
【发布时间】:2017-09-14 20:44:34
【问题描述】:

我有两列的 DataFrame:

col1     | col2

20         EUR
31         GBP
5          JPY

我可能有 10000 行这样的行

如何快速将货币转换为英镑的基础货币?

我应该使用easymoney吗? 我知道如何将转换应用于单行,但我不知道如何快速遍历所有行。

编辑: 我想申请:

def convert_currency(amount, currency_symbol):
    converted = ep.currency_converter(amount=1000, from_currency=currency_symbol, to_currency="GBP")
    return converted


df.loc[df.currency != 'GBP', 'col1'] = convert_currency(currency_data.col1, df.col2
                                                                                  )

但它还没有工作。

【问题讨论】:

  • 覆盖上述行,类似于df['col1'] = formulae*df['col1']。我想是的
  • 有没有快速的选项来使用 pandas 获取货币比率?我有 30 种不同的货币是什么?
  • 你们有汇率吗?以哪种形式?
  • 我没有。我想我可以使用easymoney。

标签: python pandas currency


【解决方案1】:
df = pd.DataFrame([[20, 'EUR'], [31, 'GBP'], [5, 'JPY']], columns=['value', 'currency'])
print df

   value currency
0     20      EUR
1     31      GBP
2      5      JPY

def convert_to_gbp(args):  # placeholder for your fancy conversion function
    amount, currency = args
    rates = {'EUR': 2, 'JPY': 10, 'GBP': 1}
    return rates[currency] * amount

df.assign(**{'In GBP': df.apply(convert_to_gbp, axis=1)})

   value currency  In GBP
0     20      EUR      40
1     31      GBP      31
2      5      JPY      50

【讨论】:

    【解决方案2】:

    在第三列加入每种货币的兑换率,加入 col2 中的货币代码。然后创建一个包含已翻译金额的列。

    dfRate:
    code | rate
    EUR    1.123
    USD    2.234
    
    df2 = pd.merge(df1, dfRate, how='left', left_on=['col2'], right_on=['code'])
    
    df2['translatedAmt'] = df2['col1'] / df2['rate']
    

    【讨论】:

    • 它只对第一个 'x' 列执行此操作,其中 'x' 等于 dfRate 的 len。
    • 对于所有以下列,它输入 NaN
    • 您是否在遍历任一 DataFrame?
    猜你喜欢
    • 2021-03-30
    • 2017-11-20
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多