pandas interpolate string 1

pandas interpolate string

import pandas as pd

s = pd.Series([None, None, 'red', 'red', None, 'blue', None, None])

print(s.to_list())
print(s.bfill().tolist())
print(s.ffill().tolist())
print(s.bfill().ffill().tolist())
print(s.ffill().bfill().tolist())
print(s.interpolate(method='pad').tolist())

Output:
[None, None, 'red', 'red', None, 'blue', None, None]
['red', 'red', 'red', 'red', 'blue', 'blue', None, None]
[None, None, 'red', 'red', 'red', 'blue', 'blue', 'blue']
['red', 'red', 'red', 'red', 'blue', 'blue', 'blue', 'blue']
['red', 'red', 'red', 'red', 'red', 'blue', 'blue', 'blue']
[None, None, 'red', 'red', 'red', 'blue', 'blue', 'blue']

Here is what the above code is Doing:
1. s.to_list() is just converting the series to a list.
2. s.bfill() is filling in the missing values with the next non-null value.
3. s.ffill() is filling in the missing values with the previous non-null value.
4. s.bfill().ffill() is filling in the missing values with the next non-null value, then filling in the remaining missing values with the previous non-null value.
5. s.ffill().bfill() is filling in the missing values with the previous non-null value, then filling in the remaining missing values with the next non-null value.
6. s.interpolate(method=’pad’) is filling in the missing values with the previous non-null value.

Similar Posts