Philipp_Kats Philipp_Kats - 1 year ago 112
Python Question

Forward fill in pandas dataframe based on specific label in a column

I need to forward feel the data within specific label (where label defined in other column:

LABEL | Col1 | ffil_col |
-------------------------
1 | N | female |
1 | M | |
2 | A | |
2 | N | male |
2 | M | |


need to be this:

LABEL | Col1 | ffil_col |
-------------------------
1 | N | female |
1 | M | female |
2 | A | |
2 | N | male |
2 | M | male |


the only Idea I have so far is to use
groupby
by label, then
ffill
each group,
and then concat everything back. Is there any alternative and more clear solution?

Answer Source

You can use transform on the groupby, which retains the same length as the original dataframe.

df['ffil_col'] = df.groupby('LABEL').ffil_col.transform(lambda group: group.ffill())

>>> df
   LABEL Col1 ffil_col
0      1    N   female
1      1    M   female
2      2    A      NaN
3      2    N     male
4      2    M     male