序列对象是可变的,因此它们不能在Python数据帧上进行散列

2024-06-01 03:37:27 发布

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

我有以下数据帧:

df1:

          Revenue    Earnings       Date
Year
2017  43206832000  4608790000 2017-01-01
2018  43462740000  8928258000 2018-01-01
2019  44268171000  5001014000 2019-01-01
2020  43126472000  4770527000 2020-01-01

我正在使用api获取excahnge货币,api为CurrencyConverter,链接为: https://pypi.org/project/CurrencyConverter/

我试图在数据框中添加一列以显示该日期的汇率,我使用了以下方法:

c.convert(100, 'EUR', 'USD', date=date(2013, 3, 21))

我的代码是:

c = CurrencyConverter()
earnings['exchange_rate'] = c.convert(1, 'BRL', 'USD', earnings['Date'])
print(earnings)

我得到的答案是:

TypeError: 'Series' objects are mutable, thus they cannot be hashed

我想得到以下信息:

        Revenue    Earnings       Date    exchange_rate
Year
2017  43206832000  4608790000 2017-01-01  0.305
2018  43462740000  8928258000 2018-01-01  0.305
2019  44268171000  5001014000 2019-01-01  0.295
2020  43126472000  4770527000 2020-01-01  0.249

Tags: 数据apiconvertdaterateexchangeyearusd
1条回答
网友
1楼 · 发布于 2024-06-01 03:37:27

尝试:

from currency_converter import CurrencyConverter

# if "Date" column isn't already converted:
df["Date"] = pd.to_datetime(df["Date"])

c = CurrencyConverter(fallback_on_missing_rate=True)    # without fallback_on_missing_rate=True I get `BRL has no rate for 2017-01-01` error.
df["exchange_rate"] = df["Date"].apply(lambda x: c.convert(1, "BRL", "USD", x))
print(df)

印刷品:

          Revenue    Earnings       Date  exchange_rate
Year                                                   
2017  43206832000  4608790000 2017-01-01       0.306034
2018  43462740000  8928258000 2018-01-01       0.304523
2019  44268171000  5001014000 2019-01-01       0.258538
2020  43126472000  4770527000 2020-01-01       0.249114

相关问题 更多 >