Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a column to an index in pandas

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?

like image 463
kasperhj Avatar asked Nov 21 '14 13:11

kasperhj


Video Answer


1 Answers

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.

like image 100
Alex Riley Avatar answered Oct 21 '22 03:10

Alex Riley