ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.
错误解决:ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.
·
错误解决:ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.
例:
data = {'Name': ['Microsoft', 'Google', 'huawei','Apple', 'Andriod'],'Shares': [63, 50, 71, 62, 65]}
data
我们的数据展示如下:
{'Name': ['Microsoft', 'Google', 'huawei', 'Apple', 'Andriod'],
'Shares': [63, 50, 71, 62, 65]}
我最开始的目的是要找到'Shares'
的取值范围在【60,75】之间的数据:
df = pd.DataFrame(data)
df[df['Shares']>60 & df['Shares']<75]
然后报错:ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
我们看一下完整的错误说明:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [34], in <cell line: 1>()
----> 1 df[df['Shares']>60 & df['Shares']<75]
File F:\anaconda\envs\sklearn-env\lib\site-packages\pandas\core\generic.py:1442, in NDFrame.__nonzero__(self)
1440 @final
1441 def __nonzero__(self):
-> 1442 raise ValueError(
1443 f"The truth value of a {type(self).__name__} is ambiguous. "
1444 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
1445 )
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
问题思考
如果不使用圆括号()对条件进行分组,Python将根据运算符优先级计算表达式,这可能会给出运算符&和~的意外结果。
df[df['Shares']>60 & df['Shares']<75]
可能会理解成df['Shares']>(60 & df['Shares'])<75
问题解决
为条件关系添加括号即可!
df[(df['Shares']>60) & (df['Shares']<75)]
更多推荐
已为社区贡献36条内容
所有评论(0)