I know about bfill and ffill to fill values in rows of the same column. But how do you do it when you need to fill values across certain multiple columns in a dataframe?
Here's the example:
Initial df:
import pandas as pd
inidf = [('Prod', ['P1', 'P2']),
('A', ['1', '1']),
('1', ['', '40']),
('2', ['10', '60']),
('3', ['30', '']),
('B', ['1', '2']),
]
df = pd.DataFrame.from_items(inidf)
df
Prod A 1 2 3 B
0 P1 1 10 30 1
1 P2 1 40 60 2
Target df:
tgtdf = [('Prod', ['P1', 'P2']),
('A', ['1', '1']),
('1', ['10', '40']),
('2', ['10', '60']),
('3', ['30', '60']),
('B', ['1', '2']),
]
df2 = pd.DataFrame.from_items(tgtdf)
df2
Prod A 1 2 3 B
0 P1 1 10 10 30 1
1 P2 1 40 60 60 2
In my example above, the columns to be targeted are Columns named 1, 2 and 3. In the first row, the first target column (named 1) has a missing value and is copied from the next populated Column in this case (named 2). In the second row, last target column (named 3) has a missing value and is copied from the previous populated Column in this case (named 2).