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

How can I transform multiple columns in a table to list

How can I transform Tab 1 to Tab2

transform Tab1 to Tab2

df = pd.DataFrame({'A': [3, 5], 'B': [4, 6], 'Z': [6, 8]}, index=[1, 100])

I suppose pandas df.melt might help, but I’m not sure

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 flatten your dataframe and manipulate index to get expected output:

out = (df.unstack().sort_index(level=1)
         .set_axis([f'{j}{i}' for i in df.index for j in df.columns])
         .rename_axis('var').rename('val').reset_index())

Output:

>>> out
    var  val
0    A1    3
1    B1    4
2    Z1    6
3  A100    5
4  B100    6
5  Z100    8
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