Home > Software engineering >  How to do null combination in pandas dataframe
How to do null combination in pandas dataframe

Time:04-08

Here's my dataset

Id    Column_A    Column_B    Column_C
1         Null           7        Null
2            8           7        Null
3         Null           8           7
4            8        Null           8

If at least one column is null, Combination will be Null

Id    Column_A    Column_B    Column_C   Combination
1         Null           7        Null         Null
2            8           7        Null         Null
3         Null           8           7         Null
4            8        Null           8         Null

CodePudding user response:

Assuming Null is NaN, we could use isna any:

df['Combination'] = df.isna().any(axis=1).map({True: 'Null', False: 'Notnull'})

If Null is a string, we could use eq any:

df['Combination'] = df.eq('Null').any(axis=1).map({True: 'Null', False: 'Notnull'})

Output:

   Id Column_A Column_B Column_C Combination
0   1     Null        7     Null        Null
1   2        8        7     Null        Null
2   3     Null        8        7        Null
3   4        8     Null        8        Null

CodePudding user response:

Use DataFrame.isna with DataFrame.any and pass to numpy.where:

df['Combination'] = np.where(df.isna().any(axis=1), 'Null','Notnull')
df['Combination'] = np.where(df.eq('Null').any(axis=1), 'Null','Notnull')
  • Related