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 to pivot a data frame with suffixed columns?

I have a pandas dataframe with the following structure:

Frame     P_1_x  P_1_y  P_2_x  P_2_y ... P_N_x P_N_y
0         1      9      6      2         4     3 

And I would like to transform it to:

      x   y
P_1   1   9 
P_2   6   2 
.
.
.
P_N   4   3

Is there any efficient way to do it with pandas?

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

I tried to use the pandas.wide_to_long() function and multi indexing but I couldn’t make it work in my case.

>Solution :

Split the columns around _ and use expand parameter to convert to multiindex, then stack the multiindex columns to reshape:

s = df.set_index('Frame')
s.columns = s.columns.str.rsplit(r'_', 1, expand=True)
out = s.stack(0).droplevel(0)

     x  y
P_1  1  9
P_2  6  2
...
P_N  4  3
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