这是一个小演示,它说明了为什么发生这种情况:
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
-熊猫不知道该怎么做时:
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().
解决方法:
我们可以决定如何处理布尔值的系列-比如if
应该返回True
,如果 的值是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