转置表,然后设置并重命名索引 [英] Transpose table then set and rename index
问题描述
我想转置一个表并重命名索引.
I want to transpose a table and rename the index.
如果显示具有现有索引Time
的df
,我将得到
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
然后在df.transpose()
之后我在
Time 1 2 3
v1 0.5 0.2 0.3
v2 0.3 0.1 0.3
有趣的是,如果我现在这样做df.Time
我会得到
Interestingly if I do now df.Time
I get
AttributeError: 'DataFrame' object has no attribute 'Time'
尽管它会显示在输出中.
although it gets displayed in the output.
我找不到一种方法可以轻松地将列Time
重命名为Variable
并将其设置为新索引..
I can't find a way to easily rename the column Time
to Variable
and set that as the new index ..
我尝试了df.reset_index().set_index("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
推荐答案
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
但是我认为您需要从index
设置新列,然后将列index
重命名为var
,还将列名重设为None
:
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
这篇关于转置表,然后设置并重命名索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!