Python使用Forex汇率转换后转int去小数报TypeError如何解决
错误原因
你调用的Python原生int()函数只能处理单个数值类型的输入,而c["Price (BRL)"]是Pandas的Series结构(对应CSV里的一整列价格数据),经过汇率运算后得到的仍然是Series对象,int()不支持对整列数据做批量类型转换,因此抛出TypeError: cannot convert the series to <class 'int'>错误。
解决方法
使用Pandas内置的astype(int)方法实现整列数据的批量整数转换即可,修改后的代码如下:
c["USD"] = ((((c["Price (BRL)"] * usd) / 2) * 2 + 1)).astype(int) c["CAD"] = ((((c["Price (BRL)"] * cad) / 2) * 2 + 1)).astype(int) c["NZD"] = ((((c["Price (BRL)"] * nzd) / 2) * 2 + 1)).astype(int)
如果你的需求只是单纯去除小数部分,不需要自定义的取整逻辑,可以直接简化为:
c["USD"] = (c["Price (BRL)"] * usd).astype(int) c["CAD"] = (c["Price (BRL)"] * cad).astype(int) c["NZD"] = (c["Price (BRL)"] * nzd).astype(int)
内容的提问来源于stack exchange,提问作者Oo'-
相关产品推荐
相关产品推荐

