将列转换为 pandas 索引 [英] Convert a column to an index in pandas

查看:87
本文介绍了将列转换为 pandas 索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的DataFrame df.

I have a DataFrame df like this.

Number SomeValue SomeOtherValue
  10    10        1.0
  11     3        1.1

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

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

  Number SomeValue SomeOtherValue
0  10    10        1.0
1  11     3        1.1

我希望Number作为我的索引,所以我要做这样的事情:

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

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?

推荐答案

您可以简单地使用

You can simply use the set_index method for this:

df.set_index('Number')

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

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.

这篇关于将列转换为 pandas 索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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