Python – Convert a column to an index in pandas

dataframepandaspython

I have a DataFrame df like this.

Number SomeValue SomeOtherValue
  10    10        1.0
  11     3        1.1

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

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?

Best Solution

You can simply use the set_index method for this:

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.