Grouped Forward Fill & Back Fill with Pandas
Python
In this snippet all NAs in the latest_value column are filled but filling only happens within each category i.e. a latest value from one category won't be used to fill an NA from a different category
1| #Forward fill 2| df['latest_value_ffill'] = df.groupby('category')['latest_value'].transform(lambda x: x.fillna(method='ffill')) 3| 4| #Back fill 5| df['latest_value_bfill'] = df.groupby('category')['latest_value'].transform(lambda x: x.fillna(method='bfill'))
133
121
116
109