(Python)在两个数组中查找值的索引,它们等于另外两个数组中的值

时间:2017-07-24 09:52:13

标签: python arrays numpy equals indices

我有以下4个数组,我想获得数组A和X中相等的值的索引,这些索引对应于B和Y中相同位置的值。因此对于以下示例,

    import numpy as np
    A = np.asarray([400.5, 100,  700,   200,  15, 900])
    B = np.asarray([500.5, 200,  500, 600.5,   8, 999])
    X = np.asarray([400.5, 700,  100,   300,  15, 555, 900])
    Y = np.asarray([500.5, 500,600.5,   100,   8, 555, 999])

我想得到两个带索引的数组:

indAB = [0 2 4 5]

  • 0因为A& B中的400.5和500.5也位于0位置的X& Y
  • 2因为A& B中的700和500也在位置2的X& Y中
  • 4因为A& B中的15和8也位于位置4的X& Y
  • 5因为A& B中的900和999也在位置5的X& Y

indXY = [0 1 4 6]

    发现
  • 0,1,4和6类似于indAB,而是相对于X& Y而言。

其中indAB是A和B中的值的索引,它们等于X和Y中的值,而indXY是X和Y中的值的索引,它们等于A和B中的值。

这是我到目前为止的尝试:

    def indices(a,b):
        setb = set(b)
        ind = [i for i, x in enumerate(a) if x in setb]
        return ind

    iA = np.asarray(indices(A,X))
    iB = np.asarray(indices(X,A))
    iX = np.asarray(indices(B,Y))
    iY = np.asarray(indices(Y,B))

    def CommonIndices(a,b):
        return np.asarray(list(set(a) & set(b)))

    indAB = CommonIndices(iA,iX)
    indXY = CommonIndices(iB,iY)

    print(indAB) # returns = [0 2 4 5]
    print(indXY) # returns = [0 1 2 4 6]

我一直得到[0 1 2 4 6]因为indXY不正确。不应该包括图2,因为即使600.5在Y和B中,A和B(分别)中的200和100也不相等。

如果有人可以为此提供解决方案,我将非常感激。非常感谢!

3 个答案:

答案 0 :(得分:2)

numpy_indexed包(免责声明:我是它的作者)包含有效和优雅地执行此类操作的功能。内存要求是线性的,并且此方法的计算要求为NlogN。对于您正在考虑的实质阵列,相对于目前接受的蛮力方法的速度优势可能很容易达到数量级:

import numpy as np
import numpy_indexed as npi

A = np.asarray([400.5, 100,  700,   200,  15, 900])
B = np.asarray([500.5, 200,  500, 600.5,   8, 999])
X = np.asarray([400.5, 700,  100,   300,  15, 555, 900])
Y = np.asarray([500.5, 500,600.5,   100,   8, 555, 999])

AB = np.stack([A, B], axis=-1)
XY = np.stack([X, Y], axis=-1)

# casting the AB and XY arrays to npi.index first is not required, but a performance optimization; without this each call to npi.indices would have to re-index the arrays, which is the expensive part
AB = npi.as_index(AB)
XY = npi.as_index(XY)
# npi.indices(list, items) is a vectorized nd-equivalent of list.index(item)
indAB = npi.indices(AB, XY, missing='mask').compressed()
indXY = npi.indices(XY, AB, missing='mask').compressed()

请注意,您也可以选择处理缺失值的方法。另请参阅set-operations,例如npi.intersection(XY,AB);他们可能会提供一条更简单的途径来达到你想达到的更高水平。

答案 1 :(得分:1)

试试这个:

import numpy as np

A = np.asarray([400.5, 100,  700,   200,  15, 900])
B = np.asarray([500.5, 200,  500, 600.5,   8, 999])
X = np.asarray([400.5, 700,  100,   300,  15, 555, 900])
Y = np.asarray([500.5, 500,600.5,   100,   8, 555, 999])

AB = np.stack([A, B], axis=-1)
XY = np.stack([X, Y], axis=-1)

eq = AB[:, np.newaxis, :] == XY[np.newaxis, :, :]
eq = np.logical_and.reduce(eq, axis=-1)

indAB, = np.where(np.logical_or.reduce(eq, axis=1))
indXY, = np.where(np.logical_or.reduce(eq, axis=0))

print("indAB", indAB)
print("indXY", indXY)

输出:

indAB [0 2 4 5]
indXY [0 1 4 6]

<强>解释

ABXY只是数组AB以及XY分别“堆叠”到二维数组中。 eqABXY中的元素进行全面反对比较; np.newaxis用于向ABXY添加维度(请注意AB在位置1获取新维度,在位置0获取XY。等于运算符==通过新维度广播数组。第一个np.logical_and.reduce是确保两个“组件”相等(AXBY),并且np.logical_or.reduce操作会检查ABXY以及XYAB之间是否存在完全相同。最后,np.where获取索引。

作为缺点,请注意这需要一个大小为len(A) x len(X) x 2的布尔数组,因此如果原始数组非常大,则可能会遇到内存问题。

<强>更新

如上所述,非常大的阵列可能是一个问题。如果你想“一次性”进行所有的比较,那么就没有办法解决它(中间数组的大小只是比较的数量)。但是,您也可以“按件”运行算法,例如:

import numpy as np

MAX_SIZE = 2  # Biggest array will be MAX_SIZE x MAX_SIZE x 2

A = np.asarray([400.5, 100,  700,   200,  15, 900])
B = np.asarray([500.5, 200,  500, 600.5,   8, 999])
X = np.asarray([400.5, 700,  100,   300,  15, 555, 900])
Y = np.asarray([500.5, 500,600.5,   100,   8, 555, 999])

AB = np.stack([A, B], axis=-1)
XY = np.stack([X, Y], axis=-1)

maskAB = np.full(len(AB), False, dtype=bool)
maskXY = np.full(len(XY), False, dtype=bool)

for iAB in range(0, len(AB), MAX_SIZE):
    pAB = np.expand_dims(AB[iAB:iAB + MAX_SIZE], axis=1)
    for iXY in range(0, len(XY), MAX_SIZE):
        pXY = np.expand_dims(XY[iXY:iXY + MAX_SIZE], axis=0)
        eq = pAB == pXY
        eq = np.logical_and.reduce(eq, axis=-1)
        maskAB[iAB:iAB + MAX_SIZE] |= np.logical_or.reduce(eq, axis=1)
        maskXY[iXY:iXY + MAX_SIZE] |= np.logical_or.reduce(eq, axis=0)

indAB, = np.where(maskAB)
indXY, = np.where(maskXY)

print("indAB", indAB)
print("indXY", indXY)

输出仍然是:

indAB [0 2 4 5]
indXY [0 1 4 6]

我使用的MAX_SIZE只是为了表明它在示例中有用,但实际上你可以根据你愿意使用的最大内存量来选择它(例如{{1}它应该是几百兆字节的数量级)。 MAX_SIZE = 10000 需要小于数组的大小,也不必是它们大小的除数。

答案 2 :(得分:1)

这是另一种方法。我敢说这是相对清楚的,它应该是有效的,因为使用集合它只需要O( len(A) + len(X) )内存。

numpy甚至不需要,但可以用于数组。

from collections import defaultdict

A = [400.5, 100, 700, 200, 15, 900]
B = [500.5, 200, 500, 600.5, 8, 999]
X = [400.5, 700, 100, 300, 15, 555, 900]
Y = [500.5, 500, 600.5, 100, 8, 555, 999]

def get_indices(values):
    d = defaultdict(set)
    for i, value in enumerate(values):
        d[value].add(i)
    return d

iA, iB, iX, iY = [get_indices(values) for values in [A, B, X, Y]]
print(iA)
# {400.5: {0}, 100: {1}, 200: {3}, 900: {5}, 700: {2}, 15: {4}}
print(iX)
# {400.5: {0}, 100: {2}, 300: {3}, 900: {6}, 555: {5}, 700: {1}, 15: {4}}

for i, (a, b) in enumerate(zip(A, B)):
    common_indices = iX[a] & iY[b]
    if common_indices:
        print("A B : %d" % i)
        print("X Y : %d" % common_indices.pop())
        print()

#   A B : 0
#   X Y : 0

#   A B : 2
#   X Y : 1

#   A B : 4
#   X Y : 4

#   A B : 5
#   X Y : 6