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 NaN
s 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