pythonpandasif-statementrun-script

Python - Pandas: IF statement based on column values


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


Solution

  • 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