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'))
Did you find this snippet useful?

Sign up for free to to add this to your code library