首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Python中,我无法使用Forex将货币换算转换为用于删除小数除法的整数

在Python中,我无法使用Forex将货币换算转换为用于删除小数除法的整数
EN

Stack Overflow用户
提问于 2021-06-11 00:17:34
回答 1查看 43关注 0票数 0

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

示例CSV:

代码语言:javascript
复制
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

和:

代码语言:javascript
复制
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的建议,用int替换了round

代码语言:javascript
复制
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

它给出一个错误:

代码语言:javascript
复制
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'>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-11 00:23:27

虽然序列上的大多数操作都是矢量化的,即pd.Series([n for n in ...]) + 1意味着pd.Series([n + 1 for n in ...]),但int()并非如此,它试图将完整的pandas.Series对象转换为整数。这不管用。

相反,您希望使用pandas方法将每个元素转换为int,例如astype()

代码语言:javascript
复制
>>> 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

我想你的乘/除2和加1是为了舍入到最近的。直接转换到int确实是向下舍入的。相反,您可以使用pd.Series.round()

代码语言:javascript
复制
>>> 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)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67924955

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档