查找向量中元素的索引

时间:2015-06-15 20:44:34

标签: python numpy

我有一个向量orig,它是一个p维向量

现在,我从这个向量中采样了c元素(有替换),我们称之为sampled_vec。基本上,sampled_vec包含来自orig的元素 现在,我想从sampled_vec找出这些元素的索引(在orig中)。 可能,一个例子可以说明这一点。

   orig = [1,2,3,4,5]
   sampled_vec = [3,1,3]

   indices = [2,0,2]

3 个答案:

答案 0 :(得分:1)

如果元素在orig中是唯一的。

indices = [orig.index(vec) for vec in sampled_vec]

答案 1 :(得分:1)

例如使用列表推导:

In [1]: orig = [1,2,3,4,5]

In [2]: sampled_vec = [3,1,3]

In [3]: indices = [orig.index(i) for i in sampled_vec]

In [4]: indices
Out[4]: [2, 0, 2]

答案 2 :(得分:0)

您可以使用np.searchsorted -

import numpy as np

out = np.searchsorted(orig, sampled_vec, side='left')

示例运行 -

In [44]: orig = [1,2,3,4,5]
    ...: sampled_vec = [3,1,3,2,5]
    ...: 

In [45]: np.searchsorted(orig, sampled_vec, side='left')
Out[45]: array([2, 0, 2, 1, 4], dtype=int64)
相关问题