1

I want to fill the value "0" of a specific row with previous value of the same row. So, the logic is that if the next value of the row is "0" then the previous value of the same row will get copied to it.

Example of the row

enter image description here

and expected result

enter image description here

The row is a part of pandas data frame. Kindly provide examples of the code. I will appreciate your help.

Thanks

rafaelc
  • 57,686
  • 15
  • 58
  • 82
Deya
  • 79
  • 1
  • 9

1 Answers1

1

You can use replace() and bfill()

import numpy as np

df['col_name'].replace(0, np.nan).bfill()

If your 0 is a string, use

df['col_name'].replace("0", np.nan).bfill()

bfill means you will fill the NaNs backwards. You can also fill forwards using ffill()

df['col_name'].replace(0, np.nan).ffill()

As noted in comments, you can also set everything at once using to_replace arg:

df.col.replace(to_replace=0, method='ffill')

Example:

df = pd.DataFrame({'col': [1,2,3,0,5,6,7,0,9]})

col
0   1
1   2
2   3
3   0
4   5
5   6
6   7
7   0
8   9

df.col.replace(0, np.nan).bfill()

0    1.0
1    2.0
2    3.0
3    5.0
4    5.0
5    6.0
6    7.0
7    9.0
8    9.0

Notice that once np.nan is a float, pandas may interpret the column to have dtype float. However, you can always set explicitly the type back to int using astype

df.col.replace(0, np.nan).bfill().astype(int)

0    1
1    2
2    3
3    5
4    5
5    6
6    7
7    9
8    9
rafaelc
  • 57,686
  • 15
  • 58
  • 82
  • 1
    You are awesome. Tons of thanks. – Deya Jul 27 '18 at 13:37
  • @Deya thank you! Glad I could help :) Please consider [Accepting the answer](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) if t helped ! – rafaelc Jul 27 '18 at 13:38
  • You can avoid the intermedate `np.nan` replacement: `df.col.replace(to_replace=0, method='bfill')`. This will also prevent the cast to `float` – user3483203 Jul 27 '18 at 13:39
  • @user3483203 nice remark crhis thanks ;) – rafaelc Jul 27 '18 at 13:41