我正在使用Pandas读取CSV文件,使用外汇将货币转换为其他货币,使用整数模式(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的建议,用int替换了round
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'>发布于 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()
>>> 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()
>>> 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)
https://stackoverflow.com/questions/67924955
复制相似问题