Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

python - Pandas Boolean .any() .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.

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]

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

This should print:

True
True

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...