BlueMango
BlueMango

Reputation: 503

Transpose Pandas dataframe and change column header

this question is a duplicate, in a sense I want exactly this.

So, basically I have following df:

Time | A | B|

1    |10 | 20|
2    |15 | 25|

I want:

Name | 1 | 2|

A    |10 | 15|
B    |20 | 25|

So, first I tried the accepted solution from the question: df = df.set_index('Time').T.rename_axis('Name').rename_axis(None, 1), but it gives me rename_axis() takes from 1 to 2 positional arguments but 3 were given. If I try only df.set_index('Time').T.rename_axis('Name'), the df becomes:

Time | 1 | 2|

Name
A    |10 | 15|
B    |20 | 25|

Even so if I print the name of first column with df.columns[0], I get 1 and neither Time nor Name. I want the first column to be Name.

How can I transpose my df in such a way? Hopefully,the question is clear!

Thanks

Upvotes: 1

Views: 1483

Answers (1)

jezrael
jezrael

Reputation: 862851

You have to specify axis=1 instead 1 (I think function in last version was changed) and add DataFrame.reset_index for convert index to column:

df = df.set_index('Time').T.rename_axis('Name').rename_axis(None, axis=1).reset_index()
print (df)
  Name   1   2
0    A  10  15
1    B  20  25

Or in last pandas version use parameters index and columns:

df = df.set_index('Time').T.rename_axis(index='Name', columns=None).reset_index()

Upvotes: 2

Related Questions