Windstorm1981
Windstorm1981

Reputation: 2680

Python Pandas: Get Index Label for a Value in a DataFrame

Short question:

I have the following (sample) dataframe:

df:

        height   weight   hair
joe       5.6     123     brown
mary      5.2     110     blonde
pete      6.0     160     red

If I know the value in 'hair' is 'blonde', how do I get the index label (not integer location) corresponding to df.ix['mary','hair']? (In other words, I want to get 'mary' knowing that hair is 'blonde').

If I wanted the integer value of the index I'd use get_loc. But I want the label.

Thanks in advance.

Upvotes: 0

Views: 7207

Answers (2)

Saurabh7
Saurabh7

Reputation: 720

If you want the first label:

df[df['hair'] == 'blonde'].index[0]

Or if you want all the values:

labels = df[df['hair'] == 'blonde'].index.values.tolist()

Upvotes: 2

FLab
FLab

Reputation: 7476

I typically do the following using np.where:

import numpy as np

idx = df.index[np.where(df['hair'] == 'blonde')]

Which gives the expected result:

Index([u'mary'], dtype='object')

If you want the result in a list, you can use .tolist() method of index

Upvotes: 1

Related Questions