python - Pandas - Dataframe.set_index - 如何保留旧的索引列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49720616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python - Pandas - Dataframe.set_index - how to keep the old index column
提问by Egirus Ornila
I have this Dataframe
:
我有这个Dataframe
:
import pandas as pd
df = pd.DataFrame({'Hugo' : {'age' : 21, 'weight' : 75},
'Bertram': {'age' : 45, 'weight' : 65},
'Donald' : {'age' : 75, 'weight' : 85}}).T
df.index.names = ['name']
age weight
name
Bertram 45 65
Donald 75 85
Hugo 21 75
I want to change the index to the column 'age'
:
我想将索引更改为列'age'
:
df.set_index('age', inplace=True)
weight
age
45 65
75 85
21 75
The old index-column name gets lost. Is there a way to change the index without losing the original index-column and getting the old column as 'normal' column again, so that it looks like this?
旧的索引列名称丢失。有没有办法在不丢失原始索引列的情况下更改索引并将旧列重新设为“正常”列,使其看起来像这样?
name weight
age
45 Bertram 65
75 Donald 85
21 Hugo 75
回答by jezrael
Use reset_index
first and then set_index
:
reset_index
先使用,然后set_index
:
df = df.reset_index().set_index('age')
print (df)
name weight
age
45 Bertram 65
75 Donald 85
21 Hugo 75
回答by YOBEN_S
Adding the append=True
and with reset_index
添加append=True
和reset_index
df.set_index('age', append=True).reset_index(level=0)
Out[80]:
name weight
age
45 Bertram 65
75 Donald 85
21 Hugo 75
回答by ricky_hehe
The below is the most efficient since it appends the new index of age
and makes sure its inplace
下面是最有效的,因为它附加了新的索引age
并确保它就位
df.set_index('age',append=True,inplace=True)
回答by pink.slash
Your DataFrame df
has name
(= 'Bertram', 'Donald', 'Hugo'
) as index
您的 DataFramedf
有name
(= 'Bertram', 'Donald', 'Hugo'
) 作为索引
That is, your df
is:
也就是说,你df
是:
age weight
name
Bertram 45 65
Donald 75 85
Hugo 21 75
You can convert the index (name
) into a new column inside your DataFrame df
by using the .reset_index()
method.
您可以将指数(转换name
)为您的数据帧中的新列df
使用.reset_index()
方法。
df.reset_index(inplace=True)
name
becomes a column and the new index is the standard default integer index:
name
成为一列,新索引是标准的默认整数索引:
Your df looks like this now:
你的 df 现在看起来像这样:
Out[1]:
name age weight
0 Bertram 45 65
1 Donald 75 85
2 Hugo 21 75
Now, you can change the index to age
with the .set_index()
method.
现在,您可以age
使用该.set_index()
方法更改索引。
df.set_index('age',inplace=True)
df
is now:
df
就是现在:
Out[2]:
name weight
age
45 Bertram 65
75 Donald 85
21 Hugo 75
As @jezraelpoints out above you can do this in a single step, instead of two steps, like this:
正如@jezrael在上面指出的,你可以一步完成,而不是两步,像这样:
df = df.reset_index().set_index('age')