Title: If Else On Any Or All Elements Slug: ifelse_on_any_or_all_elements
Summary: If Else On Any Or All Elements
Date: 2016-05-01 12:00
Category: Python
Tags: Basics
Authors: Chris Albon

Preliminaries


In [1]:
# import pandas as pd
import pandas as pd

Create a simulated dataset


In [2]:
# Create an example dataframe
data = {'score': [1,2,3,4,5]}
df = pd.DataFrame(data)
df


Out[2]:
score
0 1
1 2
2 3
3 4
4 5

Does any cell equal 3?


In [3]:
# If any element in df.score equals three,
if (df.score == 3).any():
    # Print this
    print('Does any cells equal 3? Yes!')
# Otherwise,
else:
    # Print this
    print('Does any cells equal 3? No!')


Does any cells equal 3? Yes!

Do all cells equal 3?


In [4]:
# If all elements in df.score equal three,
if (df.score == 3).all():
    # Print this
    print('Do all cells equal 3? Yes!')
# Otherwise
else:
    # Print this
    print('Do all cells equal 3? No!')


Do all cells equal 3? No!