Pandas: replace zero value with value of another column

Viewed 2075

How to replace zero value in a column with value from same row of another column where previous row value of column is zero i.e. replace only where non-zero has not been encountered yet? For example: Given a dataframe with columns a, b and c:

+----+-----+-----+----+
|    |   a |   b |  c |
|----+-----+-----|----|
|  0 |   2 |   0 |  0 |
|  1 |   5 |   0 |  0 |
|  2 |   3 |   4 |  0 |
|  3 |   2 |   0 |  3 |
|  4 |   1 |   8 |  1 |
+----+-----+-----+----+

replace zero values in b and c with values of a where previous value is zero

+----+-----+-----+----+
|    |   a |   b |  c |
|----+-----+-----|----|
|  0 |   2 |   2 |  2 |
|  1 |   5 |   5 |  5 |
|  2 |   3 |   4 |  3 |
|  3 |   2 |   0 |  3 | <-- zero in this row is not replaced because of  
|  4 |   1 |   8 |  1 |     non-zero value (4) in row before it.
+----+-----+-----+----+
1 Answers
Related