k.ko3n
k.ko3n

Reputation: 954

Do something if df does not contain specific column name

I want to do an if else operation based on non-existence of a specific column name in the df.

if a_specific_column_is_NOT_in_the_df:
   print('not ok')
else:
   print('ok')

With the following code I can do the reverse of my task.

if [col for col in df.columns if 'A' in col]:
    print('ok')
else:
    print('not ok')

My task is to print not ok if df does not contain column names A and to print ```ok`` if otherwise.

Thanks!

Upvotes: 0

Views: 639

Answers (1)

Pythoscorpion
Pythoscorpion

Reputation: 164

do it just by adding Not in front of list

 if not [col for col in df.columns if 'A' in col]:
        print('not ok')
 else:
        print('ok')

for instance this one will result not ok:

if not [col for col in ['B','C'] if 'A' in col]:
    print('not ok')
else:
    print('ok')

Upvotes: 1

Related Questions