How to transform using pandas, i.e. removing all the 0 values above 1st non zero value and replacing it with NaN but keeping 0 values if it is after?

Viewed 17
Date Item Quantity
2022-01-01 A 0
2022-01-02 B 0
2022-01-03 C 0
2022-01-04 B 5
2022-01-05 B 6
2022-01-06 B 7
2022-01-07 B 0
Date Item Quantity
2022-01-01 A NaN
2022-01-02 B NaN
2022-01-03 C NaN
2022-01-04 B 5
2022-01-05 B 6
2022-01-06 B 7
2022-01-07 B 0
1 Answers

You can use cummax to set up a mask:

df['Quantity'] = df['Quantity'].where(df['Quantity'].ne(0).cummax())

Alternative with cummin and boolean indexing:

df.loc[df['Quantity'].eq(0).cummin(), 'Quantity'] = float('nan')

output:

         Date Item  Quantity
0  2022-01-01    A       NaN
1  2022-01-02    B       NaN
2  2022-01-03    C       NaN
3  2022-01-04    B       5.0
4  2022-01-05    B       6.0
5  2022-01-06    B       7.0
6  2022-01-07    B       0.0
Related