fillna rows based on previous and next row

Viewed 95

I have this kind of df :

values
str1
str1
nan
nan
str1
nan
nan
str2
nan
nan
str2

values are str. I want to fillna where rows are surrounded by the same value and get :

values
str1
str1
str1
str1
str1
nan
nan
str2
str2
str2
str2

Is there an option in the fillna function that can do that ?

EDIT :

Is there also an option to set a limit of number of rows between two str_i to fill ?

1 Answers

One way using ffill and bfill:

df2 = df.ffill()
print(df2[df2 == df.bfill()])

Output:

   values
0    str1
1    str1
2    str1
3    str1
4    str1
5     NaN
6     NaN
7    str2
8    str2
9    str2
10   str2
Related