Dataframe group with sort

Question:

My script is currently combining multiple rows into one by using group by… however I’d also like to make sure that within each ‘src’ its sorted in ascending order by a field called ‘numb’.

df = df.astype(str).groupby('src')['source_soe_dur'].agg('|'.join).to_frame('durMerge').reset_index()

I think I probably need to do something like: https://www.statology.org/pandas-groupby-sort/ but not sure how to adapt it to my use-case.

Asked By: Tony

||

Answers:

Sorting the entire dataframe before grouping is the same as sorting within each of the groups, so we can do the following:

df = df.astype(str).sort_values("numb", ascending=True).groupby('src')['source_soe_dur'].agg('|'.join).to_frame('durMerge').reset_index()
Answered By: brusselswanny
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.