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

python pandas convert unique rows as new columns with their respective data

I have some data of the below form:

Col1    Col2        Col3    Col4
a       2021-12-11  759     46
a       2021-13-11  803     30
b       2021-12-11  46      10
b       2021-13-11  86      7

and I want to transform it to the below form:

Col2        a-Col3    a-Col4  b-col3 b-col4
2021-12-11  759       46      46     10
2021-13-11  803       30      86     7

I have tried pivot table and similar "grouping" functions but I was unable to find any solution.

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 can use:

df2 = df.set_index(['Col2', 'Col1']).unstack().swaplevel(axis=1)
df2.columns = df2.columns.map('-'.join)

output:

>>> df2.reset_index()
         Col2  a-Col3  b-Col3  a-Col4  b-Col4
0  2021-12-11     759      46      46      10
1  2021-13-11     803      86      30       7

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