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

Combining two columns as a nested list of tuples by category | python dataframe

Assume I have a dataframe: df = pd.DataFrame({"cat":["a",'a', 'b', 'c'],"A":[5, 6, 1, 4],"B":[7,8, 12, 5]})
which looks like this:

   cat  A   B
0   a   5   7
1   a   6   8
2   b   1   12
3   c   4   5

Now I want to combine column A and B based on column cat. If row['cat'] is the same, then combine row['A'] and row['B'] to list of tuples. So the above example’s desired output is: [[(5, 7), (6, 8)], [(1, 12)], [(4, 5)]]

Anyone knows how to do this?
Thank you in advance!

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

>Solution :

x = df.groupby('cat').apply(lambda x: list(zip(x['A'], x['B'])))

This gives you a series of this form:

cat
a    [(5, 7), (6, 8)]
b           [(1, 12)]
c            [(4, 5)]
dtype: object

You can do x.to_list() to get a list like in example output.

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