python

Check if a column contains zero values only in Pandas DataFrame

In this post, we are going to learn to check whether all the values of a DataFrame column are 0 or not. We will be using the column name for that.

First, create the Pandas DataFrame

We need to create a Dataframe with multiple columns and rows where we will check if a column has zero values only.

import pandas as pd

employees = [
    ['Robin', 30, 0, 'India'],
    ['Rick', 35, 0, 'US'],
    ['Tony Stark', 24, 0, 'US'],
    ['Roney', 24, 0, 'Canada'],
    ['Sumit', 24, 0, 'India'],
    ['Parek Bisth', 24, 0, 'India']
]

# create dataframe
df = pd.DataFrame(employees, columns=['Name', 'Age', 'PeerCount', 'Country'])

print(df)

Output

          Name  Age  PeerCount Country
0        Robin   30          0   India
1         Rick   35          0      US
2   Tony Stark   24          0      US
3        Roney   24          0  Canada
4        Sumit   24          0   India
5  Parek Bisth   24          0   India

Check if a column contains 0 values only

We will use the all() function to check whether a column contains zero value rows only. We will be using the below code to check that.

Check if the 'Age' column contains zero values only

# check if Age column contains 0 values only
if (df['Age'] == 0).all():
    print('All values in Age column are zero')
else:
    print('All values in Age column are not zero')

Output

All values in Age column are not zero

Check if the 'PeerCount' column contains zero values only

# check if PeerCount column contains 0 values only
if (df['PeerCount'] == 0).all():
  print('All values in PeerCount column are zero')
else:
  print('All values in PeerCount column are not zero')

Output

All values in PeerCount column are zero

Full Code Example

Was this helpful?