Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I transpose a pandas dataframe in a certain fashion?

Given a dataframe df like this:

     Col1  Col2
Key            
A       4    10
B       7    10
C       3     9

My desired data frame is

            A   B  C                   
    Col1    4   7  3
    Col2   10  10  9

Where Col1 and Col2 are the indices.

How would I specify this? I've tried:

In [419]: mydf.T.reset_index(drop=True)
Out[419]: 
Key   A   B  C
0     4   7  3
1    10  10  9

But for some reason, the Key remains. I'm not sure what it is, and I'm not sure how to get rid of it. I've also tried mydf.T.reset_index().set_index('index') but it is very unsightly.

like image 455
cs95 Avatar asked Mar 08 '23 12:03

cs95


1 Answers

we can use DataFrame.rename_axis() here:

In [24]: df.T.rename_axis(None, axis=1)
Out[24]:
       A   B  C
Col1   4   7  3
Col2  10  10  9
like image 80
MaxU - stop WAR against UA Avatar answered Apr 27 '23 12:04

MaxU - stop WAR against UA