ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.
Posted Data+Science+Insight
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.all().
目录
问题:
如果不使用圆括号()对条件进行分组,python将根据运算符优先级计算表达式,这可能会给出运算符&和~的意外结果。
因为缺少圆括号,如下语句:
df['Shares']>=100 & df['Shares']<=150
被系统解读为:
df['Shares'] >= (100 & df['Shares']) <= 150
import pandas as pd
data =
'Name': ['Microsoft Corporation', 'Google, LLC', 'Tesla, Inc.',\\
'Apple Inc.', 'Netflix, Inc.'],
'Symbol': ['MSFT', 'GOOG', 'TSLA', 'AAPL', 'NFLX'],
'Industry': ['Tech', 'Tech', 'Automotive', 'Tech', 'Entertainment'],
'Shares': [100, 50, 150, 200, 80]
df = pd.DataFrame(data)
# print(df)
df
df_filtered = df[df['Shares']>=100 & df['Shares']<=150]
print(df_filtered)
解决:
为条件关系添加括号;
df_filtered = df[(df['Shares']>=100) & (df['Shares']<=150)]
df_filtered
# print(df_filtered)
完整错误:
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-16-545c272b68ba> in <module> ----> 1 df_filtered = df[df['Shares']>=100 & df['Shares']<=150] 2 print(df_filtered) D:\\anaconda\\lib\\site-packages\\pandas\\core\\generic.py in __nonzero__(self) 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().
参考:pandas
参考:ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
以上是关于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()
python pandas进行条件筛选时出现ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.al