阵列之间的交叉索引

问题描述 投票:3回答:1

有没有一种快速的方法来对每一个元素的数组中的每个元素比较独特的标识符列表?

使用以使每一个唯一值的循环来工作,而是将被使用的方式过于缓慢。我一直在寻找一个量化的解决方案,但都没有成功。任何帮助将不胜感激!

arrStart = []
startRavel = startInforce['pol_id'].ravel()
for policy in unique_policies:
    arrStart.append(np.argwhere(startRavel == policy))

样品输入:

startRavel = [1,2,2,2,3,3]

unique_policies = [1,2,3]

示例输出:

arrStart = [[0], [1,2,3],[4,5]]

新阵列将具有相同的长度的唯一值数组,但各元件将是所有符合大数组中的唯一值的行的列表。

python numpy
1个回答
4
投票

这里有一个量化的解决方案:

import numpy as np
startRavel = np.array([1,2,2,2,3,3])
unique_policies = np.array([1,2,3])

排序startRavel使用np.argsort

ix = np.argsort(startRavel)
s_startRavel = startRavel[ix]

使用np.searchsorted在其中找到unique_policiesstartRavel被插入到十个分量订单指数:

s_ix = np.searchsorted(s_startRavel, unique_policies)
# array([0, 1, 4])

然后使用np.split拆分使用所获得的索引阵列。 np.argsort再次使用上s_ix处理非排序输入:

ix_r = np.argsort(s_ix)
ixs = np.split(ix, s_ix[ix_r][1:])
np.array(ixs)[ix_r]
# [array([0]), array([1, 2, 3]), array([4, 5])]

通用的解决方案:

让我们把它包起来所有的功能:

def ix_intersection(x, y):
    """
    Finds the indices where each unique
    value in x is found in y.
    Both x and y must be numpy arrays.
    ----------
    x: np.array
       Must contain unique values. 
       Values in x are assumed to be in y.
    y: np.array

    Returns
    -------
    Array of arrays. Each array contains the indices where a
    value in x is found in y
    """
    ix_y = np.argsort(y)
    s = np.searchsorted(y[ix_y], x)
    ix_r = np.argsort(s)
    ixs = np.split(ix_y, s[ix_r][1:])
    return np.array(ixs)[ix_r]

其他的例子

让我们试着用下面的数组:

startRavel = np.array([1,3,3,2,2,2])
unique_policies = np.array([1,2,3])

ix_intersection(unique_policies, startRavel)
# array([array([0]), array([3, 4, 5]), array([1, 2])])

另一示例中,这段时间与非排序输入:

startRavel = np.array([1,3,3,2,2,2,5])
unique_policies = np.array([1,2,5,3])

ix_intersection(unique_policies, startRavel)
# array([array([0]), array([3, 4, 5]), array([6]), array([1, 2])])
© www.soinside.com 2019 - 2024. All rights reserved.