Python 熊猫布尔值 .any() .all()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27791651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:17:06  来源:igfitidea点击:

Pandas Boolean .any() .all()

pythonpandas

提问by Anton

I kept getting ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().when trying boolean tests with pandas. Not understanding what it said, I decided to try to figure it out.

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().在尝试使用熊猫进行布尔测试时,我一直在接受。我不明白它说的是什么,我决定尝试弄清楚。

However, I am totally confused at this point.

但是,在这一点上我完全困惑。

Here I create a dataframe of two variables, with a single data point shared between them (3):

在这里,我创建了一个包含两个变量的数据框,它们之间共享一个数据点 (3):

In [75]:

import pandas as pd

df = pd.DataFrame()

df['x'] = [1,2,3]
df['y'] = [3,4,5]

Now I try all(is x less than y), which I translate to "are all the values of x less than y", and I get an answer that doesn't make sense.

现在我尝试所有(x 小于 y),我将其转换为“x 的所有值都小于 y”,我得到了一个没有意义的答案。

In [79]:

if all(df['x'] < df['y']):
    print('True')
else:
    print('False')
True

Next I try any(is x less than y), which I translate to "is any value of x less than y", and I get another answer that doesn't make sense.

接下来我尝试 any(is x less than y),我将其转换为“x 小于 y 的任何值”,我得到另一个没有意义的答案。

In [77]:

if any(df['x'] < df['y']):
    print('True')
else:
    print('False')
False

In short: what does any() and all() actually do?

简而言之: any() 和 all() 实际上是做什么的?

回答by Sergey Antopolskiy

Pandas suggests you to use Series methods any()and all(), not Python in-build functions.

熊猫建议您使用系列方法any()all(),而不是Python中,构建功能。

I don't quite understand the source of the strange output you have (I get True in both cases in Python 2.7 and Pandas 0.17.0). But try the following, it should work. This uses Series.any()and Series.all()methods.

我不太明白你所拥有的奇怪输出的来源(在 Python 2.7 和 Pandas 0.17.0 的两种情况下我都得到了 True )。但是尝试以下操作,它应该可以工作。这个用途Series.any()Series.all()方法。

import pandas as pd

df = pd.DataFrame()

df['x'] = [1,2,3]
df['y'] = [3,4,5]

print (df['x'] < df['y']).all() # more pythonic way of
print (df['x'] < df['y']).any() # doing the same thing

This should print:

这应该打印:

True
True