将基于标签的索引 (loc) 转换为基于位置的索引 (iloc)

sha*_*ker 4 python pandas

鉴于我的数据:

import numpy as np
import pandas as pd

data = pd.DataFrame(
    {
        'x': [11, 12, 13],
        'y': [21, 22, 23]
    },
    index=['a', 'b', 'c']
)
Run Code Online (Sandbox Code Playgroud)

我想找到标签对应的位置索引['a', 'c']。我通过目视检查知道它们是[0, 2],但这只能在玩具示例中实现。

“暴力”方法是

my_lab = ['a', 'c']
my_pos = (data.index == my_idx).to_numpy().nonzero()[0]
Run Code Online (Sandbox Code Playgroud)

有没有更好/更快/更优雅的方法来做到这一点?还是暴力法是唯一的方法?

jez*_*ael 7

使用Index.get_indexer

my_pos = data.index.get_indexer(my_lab)
print (my_pos)
[0 2]
Run Code Online (Sandbox Code Playgroud)

或者Index.searchsorted

my_pos = data.index.searchsorted(my_lab)
print (my_pos)
[0 2]
Run Code Online (Sandbox Code Playgroud)