Python - Pandas: IF statement based on column values

5.9k Views Asked by At

I am trying to develop an IF statement, which will - Run another python script, if there are values in [Column Name] which are equal to zero. - Else do nothing.

My original thought was to do something like

if df['column name'] == 0:

subprocess.call("python script.py", shall = True)

else:

print('No values of 0')

This gives me the following error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

If I try to specify any of these I am not really getting what I want.

To be specific I want the script to iterate over the values of a specific column and see if any of these values are = 0 and if they are I want to run another script which sends me an email warning.

Sorry if this has already been explained elsewhere but i cannot find it.

I am on Python 3.7.5 and using pandas.

Thank you for the help

2

There are 2 best solutions below

0
Umar.H On BEST ANSWER

you need to use .any to calculate the entire series as you want it to equate to True if any of the values are equal to 0

df = pd.DataFrame({'count' : [0,1,2,3]})

print(df)

   count
0      0
1      1
2      2
3      3

if df['count'].eq(0).any():
    print('do sth')
else:
    print('pass')

out:

do sth
1
jammin0921 On

I have two snippets here that might help you:

import pandas as pd
import numpy as np

df = pd.DataFrame()
df['Random_Numbers'] = np.random.randn(10)

First option:

# First: filter the list, check if it's empty, send a single email. 

if df[df['Random_Numbers'] > 0.0].empty == False:
    print('Sending Email....Email Sent')

Output:

"Sending Email....Email Sent"

------------------------------------------------------------------------------

Second Option:

# Second: iterate over each row in the dataframe, like you mentioned, check the value, send an email zero to multiple times. 

for index, row in df.iterrows():
    if row['Random_Numbers'] > 0.0:
        print('Sending Email...Email Sent')  

Output:

"Sending Email...Email Sent"
"Sending Email...Email Sent"
"Sending Email...Email Sent"
"Sending Email...Email Sent"
"Sending Email...Email Sent"