Search code examples
pythonpandasdataframenumpykeyerror

print a string if no null value is found


I find the first non value of a column using this and it works correctly

first_non = df['kst'].loc[df['kst'].first_valid_index()]
print(first_non)

This works when there is a non null value present in the column. However, if there's no non-null value present in that column, it throws an error KeyError: None.

How can I use this in an if else statement? So if there's a non null value present, I want to print it. If not, I want to print something else:

df = pd.read_excel('./test2.xlsx')
if (df['kst'].loc[df['kst'].first_valid_index()]):
    print (df['kst'].loc[df['kst'].first_valid_index()])
else:
    print('d')

Currently, this throws an error:

-->if (df['kst'].loc[df['kst'].first_valid_index()]):
...
KeyError: None

Solution

  • You may try this as an alternative.

    df = pd.read_excel('./test2.xlsx')
    try:
        print (df['kst'].loc[df['kst'].first_valid_index()])
    except:
        print('No value is found')