replace NaN with '-' sign only in specefic condition ,Python-Pandas

Viewed 50

I have a dataframe

 L1      D1     L2      D2         L3
 1.0    ABC     1.1     4.1        NaN
 NaN    NaN     1.7     NaN        NaN
 NaN    4.1     NaN     NaN        NaN
 NaN    1.8     3.2     PQR        NaN
 NaN    NaN     1.6     NaN        NaN

I want to replace all the NaN with '-' (only when the value in any column is last value in that row)

so basically my desired output will be

 L1      D1      L2      D2         L3
 1.0    ABC     1.1     4.1        -
 NaN    NaN     1.7     -          -
 NaN    4.1      -      -          -
 NaN    1.8     3.2     PQR        -
 NaN    NaN     1.6     -          -

Can someone help, Thank you in advance!

1 Answers

Here is one way:

minus_mask = df.loc[:, ::-1].notna().cumsum(axis=1).eq(0)
out = df.mask(minus_mask, "-")

where we first flip the df over the columns, look where it is not NaN and take the cumulative sum. If the cumulative sum equals 0, those places are where we should put "-" so we use mask method to put minus signs there,

to get

>>> out

    L1   D1   L2   D2 L3
0  1.0  ABC  1.1  4.1  -
1  NaN  NaN  1.7    -  -
2  NaN  4.1    -    -  -
3  NaN  1.8  3.2  PQR  -
4  NaN  NaN  1.6    -  -
Related