python- pandas -Dataframe.set_index-如何保留旧的索引列 [英] python - Pandas - Dataframe.set_index - how to keep the old index column

查看:909
本文介绍了python- pandas -Dataframe.set_index-如何保留旧的索引列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个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

我想将索引更改为列'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

推荐答案

使用 reset_index ,然后 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆