If one of my dataframe columns looks like this:
5
0
0
0
0
0
6
0
It should look like this
5
5
5
5
5
0
6
6
I know how to do it with a loop and a counter, but I am wondering how to do it without a for loop?
If one of my dataframe columns looks like this:
5
0
0
0
0
0
6
0
It should look like this
5
5
5
5
5
0
6
6
I know how to do it with a loop and a counter, but I am wondering how to do it without a for loop?
you can mask if value is 0 to get nan, use ffill with the limit parameter and fillna the rest with 0
s = pd.Series([5,0,0,0,0,0,6,0])
s_ = s.mask(s.eq(0)).ffill(limit=4).fillna(0)
print (s_)
0 5.0
1 5.0
2 5.0
3 5.0
4 5.0
5 0.0
6 6.0
7 6.0
dtype: float64
You don't even need to mask, there is the method replace that allows you to specify limit and method='ffill'. Going through Nanalso converts to float which is not needed.
import pandas as pd
df = pd.DataFrame({'a': [5, 0, 0, 0, 0, 0, 6, 0]})
# Replace 0s with forward fill and limit set to 4 elements
df2 = df.replace(0, limit=4, method='ffill')
print(df)
a
0 5
1 5
2 5
3 5
4 5
5 0
6 6
7 6