Pandas布尔值.any().all() [英] Pandas Boolean .any() .all()

查看:371
本文介绍了Pandas布尔值.any().all()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试对熊猫进行布尔测试时,我一直得到ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()..不明白它说什么,我决定设法弄清楚.

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.

但是,在这一点上,我完全感到困惑.

However, I am totally confused at this point.

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

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

In [75]:

import pandas as pd

df = pd.DataFrame()

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

现在,我尝试全部(x小于y),我将其翻译为"x的所有值均小于y",并且得到的答案没有意义.

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.

In [79]:

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

接下来,我尝试any(x小于y),我将其翻译为"x小于y的任何值",然后我得到另一个没有意义的答案.

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.

In [77]:

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

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

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

推荐答案

Pandas建议您使用Series方法any()all(),而不要使用Python内置函数.

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

我不太了解您的奇怪输出的来源(在Python 2.7和Pandas 0.17.0的两种情况下我都为True).但是尝试以下方法,它应该可以工作.这使用Series.any()Series.all()方法.

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.

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

这应该打印:

True
True

这篇关于Pandas布尔值.any().all()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆