【发布时间】:2021-12-29 00:32:15
【问题描述】:
我写了一个函数,它可以接受四个输入值并根据它产生结果
def python_function(a, b, c, d):
if [a, b, c, d].count(0) == 4:
return "NA"
average = (a + b + c + d) / (4 - [a, b, c, d].count(0))
# change to a for q1, b for q2, c for q3, d for q4
if c >= average:
if c > b:
return "G"
else:
return "S"
elif c < average:
return "B"
return "NA"
调用上述函数:
python_function(5.3,9.7,.4,0)
'B'
python_function(5.3,9.7,10.4,0)
'G
但是,当我们对 pandas 数据框的列应用相同的函数时,我们会遇到错误,我确信有一种方法可以处理逻辑运算符的浮点值,但我不知道该怎么做
数据框:
q1_profit q2_profit q3_profit q4_profit
0 89969.7 112896.7 25665.4 0
1 1.6 459.9 295.9 0
2 0.9 9.5 5.3 0
3 1396.1 1105.2 0.2 0
4 17.9 365.5 191.1 0
数据类型:
q1_profit 1600 non-null float64
q2_profit 1600 non-null float64
q3_profit 1600 non-null float64
q4_profit 1600 non-null int64
data["rating"] = python_function(data["q1_profit"],data["q2_profit"],data["q3_profit"],data["q4_profit"])
error_messages
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-51-6dba2870dd9c> in <module>
----> 1 data["rating"] = python_function(data["q1_profit"],data["q2_profit"],data["q3_profit"],data["q4_profit"])
<ipython-input-39-47792387b172> in python_function(a, b, c, d)
1 def python_function(a, b, c, d):
----> 2 if [a, b, c, d].count(0) == 4:
3 return "NA"
4
5 average = (a + b + c + d) / (4 - [a, b, c, d].count(0))
~\Anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
1476 raise ValueError("The truth value of a {0} is ambiguous. "
1477 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
-> 1478 .format(self.__class__.__name__))
1479
1480 __bool__ = __nonzero__
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
【问题讨论】:
标签: python pandas user-defined-functions