Home > OS >  Pandas Setting a flag for if value in a column is null
Pandas Setting a flag for if value in a column is null

Time:12-09

I am trying to build this on Python using an IF loop. For every value in index if there is at least one value in Scancode column, then I want to set the Flag to okay, else blank.

Index Scancode Flag
21-5447 blank
21-5447 blank
21-5450 45e7-4731-8467-1ccfd67ef9a9.1.1 okay
21-5450 okay
21-5450 4567-9093-826a0332f564.1.1 okay
21-5450 45c6-886b-070fa7ff121e.1.1 okay
21-5450 okay
21-5450 okay
21-5450 okay
21-5450 okay
21-5450 okay
21-5450 okay
21-5450 okay
21-5452 blank
21-5452 blank
21-5454 45e7-4731-8467-1ccfd67ef9a9.1.1 okay
21-5454 okay
21-5460 blank
21-5460 blank

You can now import Markdown table code directly using File/Paste table data... dialog.

CodePudding user response:

Try this:

df = df.set_index('Index')
df.loc[df.groupby('Index').filter(lambda x: ~x['Scancode'].isna().all()).index, 'Flag'] = 'okay'
df['Flag'] = df['Flag'].fillna('blank')

Output:

>>> df
                                Scancode   Flag
Index                                          
21-5447                              NaN  blank
21-5447                              NaN  blank
21-5450  45e7-4731-8467-1ccfd67ef9a9.1.1   okay
21-5450                              NaN   okay
21-5450       4567-9093-826a0332f564.1.1   okay
21-5450       45c6-886b-070fa7ff121e.1.1   okay
21-5450                              NaN   okay
21-5450                              NaN   okay
21-5450                              NaN   okay
21-5450                              NaN   okay
21-5450                              NaN   okay
21-5450                              NaN   okay
21-5450                              NaN   okay
21-5452                              NaN  blank
21-5452                              NaN  blank
21-5454  45e7-4731-8467-1ccfd67ef9a9.1.1   okay
21-5454                              NaN   okay
21-5460                              NaN  blank
21-5460                              NaN  blank
  • Related