Skip to content
Advertisement

Pandas groupby collapse 1st rows of group

I have a system that lets me export data in a table of this format: ​

JavaScript

where there are many columns like ‘data’ and they can have any values that don’t necessarily follow a pattern. I need to get the data into this format:

JavaScript

I’ve tried reading the documentation on gropuby and searching similar questions, but I can’t find a way to collapse just the 1st 2 rows of each group into 1 row.

Advertisement

Answer

Use df.replace

JavaScript

Output

JavaScript

You can optionally drop the record_id column with a .drop() at the end to get the desired output df_out

Advertisement