Grouped Forward Fill & Back Fill with Pandas

Python
Data Preprocessing

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'))
1 Upvote
Tags: Groupby | Fillna
Did you find this snippet useful?

Sign up to bookmark this in your snippet library

Normalize Windowed Time Series
Python
Data Preprocessing

Scaler | Normalize | Scale | Min-max

4
Pivoting Pandas Dataframes
Python
Data Preprocessing

Pandas

3