Pandas fill NaN in columns based on some conditions

Viewed 268

I have a pandas dataframe which consists of weekly values for a given id, looking something like :

id val_week1 val_week2 val_week3 val_week4 val_week5
1 0 0 3 2 0
2 1 0 0 2 3
3 0 0 0 0 1

I want to fill some column values as NaN. The condition here is that all values for an id, until the first non-zero value in each row must be NaN. So data-frame should look like this after the transformation :

id val_week1 val_week2 val_week3 val_week4 val_week5
1 NaN NaN 3 2 0
2 1 0 0 2 3
3 NaN NaN NaN NaN 1

I am trying to approach this by extracting the first non-zero value column for each row, and then all values prior to it can be filled as NaN. But I am not able to figure out how exactly could it be done using pandas, as I am new to it.
Any help would be appreciated.

1 Answers
temp = df.filter(like='val')
temp = temp.mask(temp.cumsum(1).eq(0), np.nan)
df.assign(**temp)
   id  val_week1  val_week2  val_week3  val_week4  val_week5
0   1        NaN        NaN        3.0        2.0          0
1   2        1.0        0.0        0.0        2.0          3
2   3        NaN        NaN        NaN        NaN          1

The idea is to cumulatively sum the values across the columns; if it is 0, replace with NAN.

Related