Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

327
Visualizações
How do I find the row # of a string index?

I have a dataframe where the indexes are not numbers but strings (specifically, name of countries) and they are all unique. Given the name of a country, how do I find its row number (the 'number' value of the index)?

I tried df[df.index == 'country_name'].index but this doesn't work.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

pd.Index.get_indexer

We can use pd.Index.get_indexer to get integer index.

idx = df.index.get_indexer(list_of_target_labels)
# If you only have single label we can use tuple unpacking here.
[idx] = df.index.get_indexer([country_name])

NB: pd.Index.get_indexer takes a list and returns a list. Integers from 0 to n - 1 indicating that the index at these positions matches the corresponding target values. Missing values in the target are marked by -1.

np.where

You could also use np.where here.

idx = np.where(df.index == country_name)[0]

list.index

We could also use list.index after converting Pd.Index to list using pd.Index.tolist

idx = df.index.tolist().index(country_name)
over 4 years ago · Santiago Trujillo Relatório

0

We can use Index.get_indexer:

df.index.get_indexer(['Peru'])

[3]

Or we can build a RangeIndex based on the size of the DataFrame then subset that instead:

pd.RangeIndex(len(df))[df.index == 'Peru']

Int64Index([3], dtype='int64')

Since we're only looking for a single label and the indexes are "all unique" we can also use Index.get_loc:

df.index.get_loc('Peru')

3

Sample DataFrame:

import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3, 4, 5]
}, index=['Bahamas', 'Cameroon', 'Ecuador', 'Peru', 'Japan'])

df:

          A
Bahamas   1
Cameroon  2
Ecuador   3
Peru      4
Japan     5
over 4 years ago · Santiago Trujillo Relatório

0

Why you don make the index to be created with numbers instead of text? Because your df can be sorted in many ways beyond the alphabetical, and you can lose the rows count. With numbered index this wouldn't be a problem.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda