如何使用pandas转换数据库中的货币

2024-05-19 00:04:01 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的问题中,一列有货币类型,另一列有值,我需要将它们转换为美元。我怎样才能用熊猫做到这一点

我的专栏如下:

enter image description here

我想要这样:

enter image description here

from currency_converter import SINGLE_DAY_ECB_URL
last_date = con.bounds['USD']
con = CurrencyConverter(SINGLE_DAY_ECB_URL)


def currency_convertor(row,new_currency='USD'):
    amount = row['Amount']
    curr = row['Currency']
    new_curr = con.convert(amount,curr,new_currency)
    return new_curr

df5 = df5.apply(lambda x: currency_convertor(x,new_currency="USD"), axis=1)

但在转换后,我得到的只是金额列 这样地 enter image description here

我想要第二张桌子


Tags: url类型new货币conamountcurrencyrow
1条回答
网友
1楼 · 发布于 2024-05-19 00:04:01

对于下面的答案,我假设您有一个数据帧df,其列名为currencyamount

我拼凑了一个demo jupyter notebook来说明这个方法

  1. 计算出数据框中的货币

    您将需要数据框中每种货币的汇率,因此您需要知道您有哪些货币

    currencies = df.currency.unique().tolist()
    currencies = dict.fromkeys(currencies, pd.NA)
    
  2. 定义每种货币的汇率

    汇率会随着时间的推移而变化,并且会根据您询问的对象而变化,因此您需要定义一个要使用的固定汇率。您可以自己手动定义这些:

    currencies['CAD'] = 1.23
    currencies['GBP'] = 0.72
    

    或者,作为It_is_Chris pointed out,您可以使用CurrencyConverter库实时自动地获取这些资源:

    from currency_converter import CurrencyConverter
    c = CurrencyConverter()
    for key in currencies:
       try:
          currencies[key] = c.convert(1, 'USD', key)
       except:
          pass
    
  3. 转换数据框中的货币

    尽量避免在数据帧中循环;内置的方法要快得多。在这种情况下,您可以使用^{}

    df['amount_conv'] = df.apply(lambda x: x.amount / currencies[x.currency], axis=1 )
    

相关问题 更多 >

    热门问题