Skip to content
Advertisement

GroupBy Column1, then get all elements with the first/last element on Column2 (Python)

JavaScript

I want to group by user_id, then get the first element of survey_id, and get all elements related to this selection

JavaScript

In the same way I want to group by user_id, then get the last element of survey_id, and get all elements related to this selection

JavaScript

Is there a quick groupby command to get this? I can do this by merging dataframes but I think there is some better way to do this in less command lines. Thank you in advance

Advertisement

Answer

Solution with no merging:

JavaScript

result:

JavaScript
JavaScript

result:

JavaScript

Idea is to calculate min / max of survey_id per user_id and compare it to survey_id at row level of df. Please note that original index of dataframe is preserved. If You need new index just add at the end:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement