I've this issue with this dataframe Below the code
import numpy as np
import pandas as pd
from numpy import nan
tostk = np.asarray([['A', nan, 6.0, nan, nan],
['A', 3.0, nan, nan, nan],
['A', nan, nan, 9.0, nan],
['A', nan, 5.0, nan, nan],
['A', nan, nan, nan, 7.0],
['B', nan, 8.0, nan, 7.0],
['B', nan, nan, 6.0, nan],
['B', 6.0, nan, nan, 8.0],
['B', 5.0, nan, nan, 6.0],
['B', nan, nan, 4.0, nan]])
pd.DataFrame(tostk)
I need to replace the nan values for each category (A and B) with the first value So I tried bfill but the problem with "bfill" is if the value belongs to category B it will fill the values in category A
Expected Result
res = np.asarray([['A', 3.0, 6.0, 9.0, 7.0],
['A', 3.0, 5.0, 9.0, 7.0],
['A', nan, 5.0, 9.0, 7.0],
['A', nan, 5.0, nan, 7.0],
['A', nan, nan, nan, 7.0],
['B', 6.0, 8.0, 6.0, 7.0],
['B', 6.0, nan, 6.0, 8.0],
['B', 6.0, nan, 4.0, 8.0],
['B', 5.0, nan, 4.0, 6.0],
['B', nan, nan, 4.0, nan]])
pd.DataFrame(res)
Any ideas are welcome