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

Merge lists in columns in pandas dataframe

I’ve got a dataframe with lists in two columns. It looks like this:

    column1    column2             column3
0   text       [cat1,cat2,cat3]    [1,2,3]
1   text2      [cat2,cat3,cat1]    [4,5,6]

The values in column3 belong to the categories in column2. How can I get a dataframe that looks like this?

    column1    cat1     cat2      cat3
0   text         1        2         3
1   text2        6        4         5

Thank you for your help!

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 :

You could use explode to break the values in your lists into separate rows and use pivot_table:

df.explode(
    ['column2','column3']
    ).pivot_table(index='column1',columns='column2',values='column3',aggfunc='first').reset_index()

prints:

index     column1 cat1 cat2 cat3
0          text    1    2    3
1         text2    6    4    5
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