在 Pandas 中将列转换为索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27062908/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:41:44  来源:igfitidea点击:

Convert a column to an index in pandas

pythonpandasdataframe

提问by kasperhj

I have a DataFrame dflike this.

我有一个df这样的 DataFrame 。

Number SomeValue SomeOtherValue
  10    10        1.0
  11     3        1.1

when I look at the data frame using df.head(), I get this

当我查看使用的数据框时df.head(),我得到了这个

  Number SomeValue SomeOtherValue
0  10    10        1.0
1  11     3        1.1

I would like Numberto be my index, so I do something like this:

我想Number成为我的索引,所以我做这样的事情:

df.index = df.Number
df = df.drop('Number', 1);

This seems a bit clumsy, so is there another way of promoting a column to an index?

这看起来有点笨拙,那么是否有另一种将列提升为索引的方法?

回答by Alex Riley

You can simply use the set_indexmethod for this:

您可以简单地使用该set_index方法:

df.set_index('Number')

This take the column out of the DataFrame and sets it as the DataFrame's index. The method also allows you to quickly set multiple columns as indexes or check whether the new index contains duplicates.

这将从 DataFrame 中取出列并将其设置为 DataFrame 的索引。该方法还允许您快速将多列设置为索引或检查新索引是否包含重复项。