'Python Pandas: populate a column until a different value appears?

I am working on an algo trading project using the pandas and numpy libraries and would like to achieve the following result:

Current output:

1
0
0
2
0
2
0
0
4
0
0
0
5

desired output:

1
1
1
2
2
2
2
2
4
4
4
4
5

How do I go about this?



Solution 1:[1]

Replace 0 by NA then fill forward:

df['col1'] = df['col1'].replace(0, pd.NA).ffill()
print(df)

# Output
    col1
0      1
1      1
2      1
3      2
4      2
5      2
6      2
7      2
8      4
9      4
10     4
11     4
12     5

Solution 2:[2]

You can try the method argument of pandas.DataFrame.replace

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

    col
0     1
1     1
2     1
3     2
4     2
5     2
6     2
7     2
8     4
9     4
10    4
11    4
12    5

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Corralien
Solution 2 Ynjxsjmh