如何找到字符串索引的行号?

How do I find the row # of a string index?

我有一个数据框,其中索引不是数字而是字符串(特别是国家名称),它们都是唯一的。给定一个国家的名称,我如何找到它的行号(索引的 'number' 值)?

我试过 df[df.index == 'country_name'].index 但这行不通。

pd.Index.get_indexer

我们可以使用pd.Index.get_indexer来获取整数索引。

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

您也可以在此处使用 np.where

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

list.index

我们也可以使用list.index after converting Pd.Index to list using pd.Index.tolist

idx = df.index.tolist().index(country_name)

我们可以使用Index.get_indexer:

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

[3]

或者我们可以根据 DataFrame 的大小构建一个 RangeIndex,然后对其进行子集化:

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

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

因为我们只寻找一个标签并且索引是“所有唯一的”我们也可以使用 Index.get_loc:

df.index.get_loc('Peru')

3

示例数据帧:

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

为什么不使用数字而不是文本来创建索引?因为您的 df 可以按字母顺序以外的多种方式进行排序,并且您可能会丢失行数。 使用编号索引,这不是问题。