Home > Software engineering >  print a string if no null value is found
print a string if no null value is found

Time:10-12

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

CodePudding user response:

Standard way would be try/catch as Kenny commented:

try:
   print(df['kst'].loc[df['kst'].first_valid_index()])
except:
   print("no nan values")

If you insist on if/else, check the valid index first:

valid_idx = df['kst'].first_valid_index()
print(df.loc[valid_idx, 'kst'] if valid_idx is not None else "no nan values")

CodePudding user response:

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')
  • Related