How do I fill repeating null values with a preceding non-null value?
JavaScript
x
2
1
df = pd.DataFrame(['a','a', None, 'b', None, None])
2
For instance, the data frame above would be populated as:
[‘a’,’a’,’a’,’b’,’b’,’b’]
Advertisement
Answer
Use df.fillna with the ffill
method, as follows:
JavaScript
1
2
1
df.fillna(method='ffill')
2
Example:
JavaScript
1
10
10
1
>>> df = pd.DataFrame(['a','a', None, 'b', None, None])
2
>>> df.fillna(method='ffill')
3
0
4
0 a
5
1 a
6
2 a
7
3 b
8
4 b
9
5 b
10