I want to ffill and bfill a specific column after a groupby.
My solution works:
import numpy as np
import pandas as pd
df = pd.DataFrame({
"A": [1, 1, 1, 1, 2, 2, 2, 2],
"B": [np.nan, 'f1', 'b1', np.nan, np.nan, 'f2', 'b2', np.nan]
})
df['B'] = df.groupby('A')['B'].apply(lambda _: _.ffill().bfill())
So this:
A B
0 1 NaN
1 1 f1
2 1 b1
3 1 NaN
4 2 NaN
5 2 f2
6 2 b2
7 2 NaN
Becomes this:
A B
0 1 f1
1 1 f1
2 1 b1
3 1 b1
4 2 f2
5 2 f2
6 2 b2
7 2 b2
Note that the sequences I want to ffill and bfill will always be in this format (Nan, x, y, Nan)
While this works, it's extremely slow on large dataframes.
I'm looking for some optimization to make this faster (ideally without resorting to using Dask or multiprocessing), maybe there's a Numpy optimization I can make?
I havn't had a lot of luck looking at other answers, like this one.