python - Forward fill in pandas dataframe based on specific label in a column -
i need forward feel data within specific label (where label defined in other column:
label | col1 | ffil_col | ------------------------- 1 | n | female | 1 | m | | 2 | | | 2 | n | male | 2 | m | |
need this:
label | col1 | ffil_col | ------------------------- 1 | n | female | 1 | m | female | 2 | | | 2 | n | male | 2 | m | male |
the idea have far use groupby
label, ffill
each group, , concat back. there alternative , more clear solution?
you can use transform
on groupby, retains same length 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 nan 3 2 n male 4 2 m male
Comments
Post a Comment