Wallace
Wallace

Reputation: 11

Filling na in a column in pandas from multiple columns conition

I would love to fill na in pandas dataframe where two columns in the dataframe both has on the same row.

A B C
2 3 5
Nan nan 7
4 7 9
Nan 4 9
12 5 8
Nan Nan 6

In the above dataframe, I would love to replace just row where both column A and B has Nan with "Not Available"

Thus:

A B C
2 3 5
Not available not available 7
4 7 9
Nan 4 9
12 5 8
Not available not available 6

I have tried multiple approach but I am getting undesirable result

Upvotes: 0

Views: 306

Answers (1)

jezrael
jezrael

Reputation: 862601

If want test only A and B columns use DataFrame.loc with mask test it missing value with DataFrame.all for test if both are match:

m = df[['A','B']].isna().all(axis=1)

df.loc[m, ['A','B']] = 'Not Available'

If need test any 2 columns first count number of missing values and is 2 use fillna:

m = df.isna().sum(axis=1).eq(1)

df = df.where(m, df.fillna('Not Available'))
print (df)
               A              B  C
0              2              3  5
1  Not Available  Not Available  7
2              4              7  9
3            NaN              4  9
4             12              5  8
5  Not Available  Not Available  6

Upvotes: 1

Related Questions