kasperhj
kasperhj

Reputation: 10482

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?

Upvotes: 12

Views: 26719

Answers (1)

Alex Riley
Alex Riley

Reputation: 177048

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.

Upvotes: 28

Related Questions