我无法使用 Forex 将货币转换转换为去除小数部分的整数,在 Python

I can not convert the currency conversion, using Forex, to the integer for removing the decimal division, in Python

我正在使用Pandas读取CSV文件,Forex将货币转换为其他货币,整数模式(int)去除小数部分,但它给出了一个错误。

CSV 样本:

Item,Price (BRL)
Dining devices,100
Dishwasher,600
Electric shower,200
Fridge,1600
Induction cooktop cooker,1800
Kitchen cabinet,900
Kit pans,200
Microwave,700

并且:

import pandas as pd
from forex_python.converter import CurrencyRates
from pandas.io.parsers import read_csv

cc = CurrencyRates()

cad = cc.convert('BRL', 'CAD', 1)
nzd = cc.convert('BRL', 'NZD', 1)
usd = cc.convert('BRL', 'USD', 1)

c = read_csv('data/purchases.csv')
c.loc["Total"] = c.sum()
c["Item"].values[-1] = "  "

我按照 Python: Remove division decimal:

的建议将 round 替换为 int
c["USD"] = int((((c["Price (BRL)"] * usd) / 2) * 2 + 1))
c["CAD"] = int((((c["Price (BRL)"] * cad) / 2) * 2 + 1))
c["NZD"] = int((((c["Price (BRL)"] * nzd) / 2) * 2 + 1))
c

报错:

TypeError: cannot convert the series to <class 'int'>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-c0af80ffd537> in <module>
     14 c["Item"].values[-1] = "  "
     15 
---> 16 c["USD"] = int((((c["Price (BRL)"] * usd) / 2) * 2 + 1))
     17 c["CAD"] = int((((c["Price (BRL)"] * cad) / 2) * 2 + 1))
     18 c["NZD"] = int((((c["Price (BRL)"] * nzd) / 2) * 2 + 1))

~/GitLab/Gustavo/global/.env/lib/python3.9/site-packages/pandas/core/series.py in wrapper(self)
    139         if len(self) == 1:
    140             return converter(self.iloc[0])
--> 141         raise TypeError(f"cannot convert the series to {converter}")
    142 
    143     wrapper.__name__ = f"__{converter.__name__}__"

TypeError: cannot convert the series to <class 'int'>

虽然序列上的大多数操作都是向量化的,即 pd.Series([n for n in ...]) + 1 表示 pd.Series([n + 1 for n in ...]),但 int() 并非如此,它试图将完整的 pandas.Series对象为一个整数。那不行。

相反,您想要一种 pandas 将每个元素转换为 int 的方法,例如尝试 astype()

>>> df['Price (BRL)'] * usd
0     20.0
1    120.0
2     40.0
3    320.0
4    360.0
5    180.0
6     40.0
7    140.0
Name: Price (BRL), dtype: float64
>>> (df['Price (BRL)'] * usd).astype(int)
0     20
1    120
2     40
3    320
4    360
5    180
6     40
7    140
Name: Price (BRL), dtype: int64

我想您的 multiplication/division 乘以 2 并加 1 是为了四舍五入到最接近的值。直接转换为 int 确实会向下舍入。相反,您可以使用 pd.Series.round():

>>> pd.Series([.6]).astype(int)
0    0
dtype: int64
>>> pd.Series([.6]).round().astype(int)
0    1
dtype: int64

所以您想要实现的可能是 (df['Price (BRL)'] * usd).round().astype(int)