给定一些数据
In [1]: import numpy as np
In [2]: x = np.array(['a', 'b', 'b', 'a'])
和排序的索引
In [3]: i = np.array(['a', 'b'])
我想找到索引中每个数据条目的位置
In [4]: # solution here
array([0, 1, 1, 0])
这有点像分类法。我不想在这里使用熊猫。我想对固定长度的字符串执行此操作。我需要这样做有些效率。
python大神给出的解决方案
您可以使用np.searchsorted
:
>>> np.searchsorted(i, x)
array([0, 1, 1, 0])
该函数找出x
的每个元素应放置在i
中的索引,以保持排序顺序。