Home > Software design >  pandas fillna specific columns based on condition
pandas fillna specific columns based on condition

Time:11-03

Below is an example of my DF

col1      col2     col3    col4 
Comp1     False    01St    97
Comp2     False    02St    97
Comp3     True     03St    97
Comp4     False    04St    97

The Aim would be to fillna col3 & col4 when col2 == True

Below is what I've tried so far

cols = df.columns.tolist()[-2]
df[cols] = np.where(df.col2 == True, np.nan, df[cols])

The expected ouput

col1      col2     col3    col4 
Comp1     False    01St    97
Comp2     False    02St    97
Comp3     True     NaN     NaN
Comp4     False    04St    97

CodePudding user response:

Try

# two last columns
cols = df.columns[-2:]
df[cols] = df[cols].mask(df['col2'])

or assignment with iloc:

# 2 not 3
df.iloc[df['col2'], 2:] = np.nan

Output:

    col1   col2  col3  col4
0  Comp1  False  01St  97.0
1  Comp2  False  02St  97.0
2  Comp3   True   NaN   NaN
3  Comp4  False  04St  97.0
  • Related