这种报错一般是对series做了if判断。
说一下我的例子,python自带的round函数,四舍五入是向下取整。公司同事写了一个向上取整的round方法。代码如下:
def round( number, ndigits=0):
exp = number * 10 ** ndigits
if abs(abs(exp) - abs(math.floor(exp))) < 0.5:
return type(number)(math.floor(exp) / 10 ** ndigits)
return type(number)(math.ceil(exp) / 10 ** ndigits)
可以看出这个round函数当中有if判断。因为if做判断如果没有指定数据类型,会首先做bool类型的判断,而pandas重写了bool的方法,代码如下:
@final
def __nonzero__(self):
raise ValueError(
f"The truth value of a {type(self).__name__} is ambiguous. "
"Use a.empty, a.bool(), a.item(), a.any() or a.all()."
)
__bool__ = __nonzero__
可以看出panas重写了bool方法,直接raise一个ValueError。如果要修改根据错误提示,取对应轴的数值即可。
代码如下
import math
import pandas as pd
def round( number, ndigits=0):
"""强制四舍五入"""
exp = number * 10 ** ndigits
if abs(abs(exp) - abs(math.floor(exp))).all(axis=0) < 0.5:
return type(number)(math.floor(exp) / 10 ** ndigits)
return type(number)(math.ceil(exp) / 10 ** ndigits)
mk = [{"金额": 150, "数值": 12}]
data = pd.DataFrame(mk)
data['采购价'] = round(data['金额'] / data['数量'], 2)
print(data)
这样也可以执行,但是如果一个数组当中数据量大于2及以上就会报另一种错误。
raise TypeError(f"cannot convert the series to {converter}")
TypeError: cannot convert the series to <class 'float'>
这种我查了一下说是我的数据当中存在空值,但我也不知道如何处理这种。如果用python自带round也是不会报错的,因为python自带round方法是用C写的。另一种解决方法就是使用numpy自带的round也可以解决。
from numpy import around
data['采购价'] = around(data['金额']/data['数量'], 2)
这样也可以解决。但我更想求助广大网友,有没有从python层次解决这个问题的方法。