Home > Enterprise >  Replace value until different value comes pandas
Replace value until different value comes pandas

Time:08-02

My data is

data = pd.DataFrame({'a': [1,0,0,0,2,0,0,3]})

Now, data output is

   a
0  1
1  0
2  0
3  0
4  2
5  0
6  0
7  3

I want 0 replace the count number like

   a new
0  1  1
1  0  1
2  0  1
3  0  1
4  2  2
5  0  2
6  0  2
7  3  3

Replace value as counting number until different count come.

Thank you for helping me!

CodePudding user response:

You can mask and ffill:

data['new'] = data['a'].mask(data['a'].eq(0)).ffill(downcast='infer')

output:

   a  new
0  1    1
1  0    1
2  0    1
3  0    1
4  2    2
5  0    2
6  0    2
7  3    3

Alternative if the non-zero values are always increasing, use cummax:

data['new'] = data['a'].cummax()

CodePudding user response:

Try this,

df.loc[df['a'].ne(0), 'new'] = df['a']
df['new'] = df['new'].fillna(method='ffill')

O/P:

   a  new
0  1  1.0
1  0  1.0
2  0  1.0
3  0  1.0
4  2  2.0
5  0  2.0
6  0  2.0
7  3  3.0

Explanation:

  1. Mask 0 values and apply original value ('a')
  2. Fillna with forward filling
  • Related