错误:系列的真实值不明确-Python pandas [英] Error: The truth value of a Series is ambiguous - Python pandas
问题描述
我知道之前曾有人问过这个问题,但是当我尝试执行if
语句时却遇到错误.我看着这个
I know this question has been asked before, however, when I am trying to do an if
statement and I am getting an error. I looked at this link , but did not help much in my case. My dfs
is a list of DataFrames.
我正在尝试以下方法,
for i in dfs:
if (i['var1'] < 3.000):
print(i)
给出以下错误:
ValueError:系列的真值不明确.使用a.empty,a.bool(),a.item(),a.any()或a.all().
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
AND 我尝试了以下操作,并得到了相同的错误.
AND I tried the following and getting the same error.
for i,j in enumerate(dfs):
if (j['var1'] < 3.000):
print(i)
我的var1
数据类型是float32
.我没有使用任何其他logical
运算符和&
或|
.在上面的链接中,这似乎是因为使用了逻辑运算符.为什么我会得到ValueError
?
My var1
data type is float32
. I am not using any other logical
operators and &
or |
. In the above link it seemed to be because of using logical operators. Why do I get ValueError
?
推荐答案
下面是一个小演示,它说明了为什么发生这种情况:
Here is a small demo, which shows why this is happenning:
In [131]: df = pd.DataFrame(np.random.randint(0,20,(5,2)), columns=list('AB'))
In [132]: df
Out[132]:
A B
0 3 11
1 0 16
2 16 1
3 2 11
4 18 15
In [133]: res = df['A'] > 10
In [134]: res
Out[134]:
0 False
1 False
2 True
3 False
4 True
Name: A, dtype: bool
当我们尝试检查此类系列是否为True
时-熊猫不知道该怎么做:
when we try to check whether such Series is True
- Pandas doesn't know what to do:
In [135]: if res:
...: print(df)
...:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
...
skipped
...
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
解决方法:
我们可以决定如何处理一系列布尔值-例如,如果所有值为True
,则if
应该返回True
:
we can decide how to treat Series of boolean values - for example if
should return True
if all values are True
:
In [136]: res.all()
Out[136]: False
或至少一个值为True时:
In [137]: res.any()
Out[137]: True
In [138]: if res.any():
...: print(df)
...:
A B
0 3 11
1 0 16
2 16 1
3 2 11
4 18 15
这篇关于错误:系列的真实值不明确-Python pandas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!