Pandas - grouping IDs of each repeatable class and putting them in a list in column

Viewed 25

I feel like this is a simply question, but I do not use pandas that often. Suppose I have a dataframe like this:

d = {'repeat': [23, 25,23], 'unique': [1,2,3]}
df = pd.DataFrame(data=d)

How do I obtain, using pandas built-in function a dataframe of this form:

grouped = {'unique': [[1,3],[2]], 'repeat': [23,25]}
dg =pd.DataFrame(data=grouped)

df -- pandas built-in operations --> dg?

Thanks

1 Answers

You can use the groupby and agg:

df.groupby("repeat").agg(lambda x: list(x)).reset_index()
Related