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?
CodePudding user response:
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
CodePudding user response:
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