1

I have a python Data Frame how can I Find the Index number of any Label.

df.loc['Brazil']

I have the Label but I want to know the index number so I can use the df.iloc[] method.

Dataset I am working on

2
  • pls post a sample of your dataframe Commented Aug 14, 2021 at 8:15
  • posted the dataframe sample @gtomer Commented Aug 14, 2021 at 8:42

3 Answers 3

1

Assuming this input:

df = pd.DataFrame({'col': None}, index=['Argentina', 'Brazil', 'Columbia']) 
 col Argentina None Brazil None Columbia None 

You can use get_loc: df.index.get_loc('Brazil') -> outputs 1

However, this assumes a non duplicated index. If you have:

 col Argentina None Brazil None Columbia None Brazil None 

This will output: array([False, True, False, True]).

In this case, you can use the nonzero method of the output numpy array:

>>> df.index.get_loc('Brazil').nonzero()[0] array([1, 3]) 
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming you meant label as columns, you can do

index = df.columns.get_loc('Brazil') 

Comments

0

You did not post your dataframe but suppose the column in which you are searching is 'country', then:

df.index[df['country'] == 'Brazil'].to_list() 

Will give you back the index of the at which the country is Brazil

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.