Luiza Butzge
Luiza Butzge

Reputation: 1

how can I keep the value of previous cell if the next is 0 in pandas dataframe?

Hey I'm trying to keep the value of the column A if the next cell is 0 into column B

so I have this:

A B
5 5
0 0
0 0
10 10

And I want this:

A B
5 5
0 5
0 5
10 10

can someone help me?

Upvotes: 0

Views: 27

Answers (1)

Vishnudev Krishnadas
Vishnudev Krishnadas

Reputation: 10960

Use forward fill after replacing 0 with NaN

df['B'] = df.B.replace(0, np.nan).ffill(downcast='infer')

Output

    A     B
0   5   5.0
1   0   5.0
2   0   5.0
3  10  10.0

Don't forget to import numpy

import numpy as np

Upvotes: 1

Related Questions