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

Transform a dataframe in this specific way

(Please help me to rephrase the title. I looked at questions with similar titles but they are not asking the same thing.)

I have a dataframe like this:

        A       B       C
0       1       4       7   
1       2       5       8   
2       3       6       9   

(the first column is indexes and not important)

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 need to transform it so it ends up like this:

A    A-1    A-2    B    B-1    B-2    C    C-1    C-2
1    2      3      4    5      6      7    8      9

I know about DataFrame.T which seems one step in the right direction, but how to programatically change the column headers, and move the rows "besides each other" to make it a single row?

>Solution :

First use DataFrame.unstack with convert values to one columns DataFrame by Series.to_frame and transpose, last flatten MultiIndex in list comprehension with if-else for expected ouput:

df1 = df.unstack().to_frame().T
df1.columns = [a if b == 0 else f'{a}-{b}' for a, b in df1.columns]
print (df1)
   A  A-1  A-2  B  B-1  B-2  C  C-1  C-2
0  1    2    3  4    5    6  7    8    9
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