Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Group by the all the columns except the first one, but aggregate as list the first column

Let’s say, I have this dataframe:

df = pd.DataFrame({'col_1': ['yes','no'], 'test_1':['a','b'], 'test_2':['a','b']})

What I want, is to group by all the columns except the first one and aggregate the results where the group by is the same.

This is what I’m trying:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

col_names = df.columns.to_list()

df_out = df.groupby([col_names[1:]])[col_names[0]].agg(list)

This is my end data frame goal:

df = pd.DataFrame({'col_1': [['yes','no']], 'test_1':['a'], 'test_2':['b']})

And, if I have more rows, I want it to behave with the same principle, join in list the groups that are the same based on the column [1:] (from the second till end.

>Solution :

Using pandas agg() method

df = df.groupby(df.columns.difference(["col_1"]).tolist()).agg(
    {"col_1" : "first"}).reset_index()
print(df)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading