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

旧索引列名称丢失。有没有办法在不丢失原始索引列并将旧列再次作为“正常”列的情况下更改索引,以便它看起来像这样?

      name       weight
age
45   Bertram    65
75   Donald     85
21   Hugo       75

原文由 Egirus Ornila 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 801
2 个回答

先使用 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

原文由 jezrael 发布,翻译遵循 CC BY-SA 3.0 许可协议

添加 append=Truereset_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

原文由 BENY 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题