您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

错误:系列的真实值不明确-Python pandas

错误:系列的真实值不明确-Python pandas

这是一个小演示,它说明了为什么发生这种情况:

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
python 2022/1/1 18:41:39 有356人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶