Stefan Falk
Stefan Falk

Reputation: 25397

Transpose table then set and rename index

I want to transpose a table and rename the index.

If I display the df with existing index Time I get

Time  v1   v2
1     0.5  0.3
2     0.2  0.1
3     0.3  0.3

and after df.transpose() I'm at

Time  1    2    3
v1    0.5  0.2  0.3
v2    0.3  0.1  0.3

Interestingly if I do now df.Time I get

AttributeError: 'DataFrame' object has no attribute 'Time'

although it gets displayed in the output.

I can't find a way to easily rename the column Time to Variable and set that as the new index ..

I tried df.reset_index().set_index("index") but what I get is something that looks like this:

Time   1    2    3
index
v1     0.5  0.2  0.3
v2     0.3  0.1  0.3

Upvotes: 5

Views: 5891

Answers (1)

jezrael
jezrael

Reputation: 862671

You need only rename column names by rename_axis:

print (df.transpose().rename_axis('Variable', axis=1))
Variable    1    2    3
v1        0.5  0.2  0.3
v2        0.3  0.1  0.3

Or set new column names by assign name:

df1 = df.transpose()
df1.columns.name = 'Var'
print (df1)
Var    1    2    3
v1   0.5  0.2  0.3
v2   0.3  0.1  0.3

But I think you need set new column from index and then rename column index to var, also reset column names to None:

df1 = df.transpose().reset_index().rename(columns={'index':'var'})
df1.columns.name = None
print (df1)
  var    1    2    3
0  v1  0.5  0.2  0.3
1  v2  0.3  0.1  0.3

Upvotes: 7

Related Questions