I need to cleanup some data in a Pandas DataFrame and struggling with this.
Sample data:
Date | ID | Name | Address
-----------------------------------------------------------------------------------------------
1-4-1987 | 124578 | T.Hilpert | 518 Hessel Plaza Lake Lonzo, AZ 11863
23-6-1990 | 947383 | Birdie Reynolds | 964 Weissnat Green Suite 568 Rennerbury
12-5-1960 | 746732 | Earline Schulist | 57367 Alfredo Vista East Bertaburgh
9-9-2010 | 947383 | Birdie Reynolds | 964 Weissnat Green Suite 568 Rennerbury, WV 16241-5205
27-12-2017 | 124578 | Theresia Hilpert | 518 Hessel Plaza Lake Lonzo
What I want to do is this. Group by ID, get the name from the most recent date AND get the longest address string. Use these for all occurrences of the ID (in two new columns: Name_new
and Address_New
). Pleas find desired sample below:
Date | ID | Name | Address | Name_New | Address_New
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
27-12-2017 | 124578 | Theresia Hilpert | 518 Hessel Plaza Lake Lonzo | Theresia Hilpert | 518 Hessel Plaza Lake Lonzo, AZ 11863
1-4-1987 | 124578 | T. Hilpert | 518 Hessel Plaza Lake Lonzo, AZ 11863 | Theresia Hilpert | 518 Hessel Plaza Lake Lonzo, AZ 11863
23-6-1990 | 947383 | Birdie Reynolds | 964 Weissnat Green Suite 568 Rennerbury | Birdie Reynolds | 964 Weissnat Green Suite 568 Rennerbury, WV 16241-5205
9-9-2010 | 947383 | Birdie Reynolds | 964 Weissnat Green Suite 568 Rennerbury, WV 16241-5205 | Birdie Reynolds | 964 Weissnat Green Suite 568 Rennerbury, WV 16241-5205
12-5-1960 | 746732 | Earline Schulist | 57367 Alfredo Vista East Bertaburgh | Earline Schulist | 57367 Alfredo Vista East Bertaburgh
I've tried this but cant get it combined to get the desired result.
def f1(s):
return max(s, key=len)
df_new = df['New_Address'] = df.groupby('ID').agg({'Address': f1})
df_new = df[df.groupby('ID').Date.transform('max') == df['Date']]
Your help is particularly appreciated.