繁体   English   中英

python中nd数组的逻辑索引

[英]Logical indexing in python for nd arrays

我试图从(N x N x N) numpy 数组中提取所有索引,其中 A 和 B 数组中的值都等于某个值x - 找到共同的重叠。

我正在尝试:

   A[A==1 and B==1]

但得到一个错误:

ValueError:包含多个元素的数组的真值不明确。 使用 a.any() 或 a.all()

我该如何解决这个问题?

Numpy 不能重载“and”关键字。 然而,它为此重载了二元 AND 运算符 & 。 尝试:

A[(A==1) & (B==1)]

括号很重要。 我发现它通常(并不总是)比 logic_and 更易读

A == 1B == 1是布尔数组,而(A==1)*(B==1)是整数数组。 您可以通过 NumPy 的where找到该数组的非零条目:

np.where((A==1)*(B==1))

演示

考虑以下 3 维数组,这些数组随机填充了值-101

In [1066]: import numpy as np

In [1067]: np.random.seed(2016)  # this is to get the same results on multiple runs

In [1068]: N = 3
      ...: A = np.random.randint(low=-1, high=2, size=(N, N, N))
      ...: B = np.random.randint(low=-1, high=2, size=(N, N, N))

In [1069]: A
Out[1069]: 
array([[[ 1,  1,  0],
        [-1,  1, -1],
        [-1, -1, -1]],

       [[ 0,  1,  1],
        [-1,  1,  1],
        [ 0,  1,  0]],

       [[ 0,  1,  0],
        [-1,  1,  1],
        [-1,  1,  0]]])

In [1070]: B
Out[1070]: 
array([[[-1,  0,  0],
        [-1, -1,  1],
        [ 0, -1, -1]],

       [[-1, -1, -1],
        [-1,  1,  1],
        [-1,  1,  1]],

       [[ 1,  1, -1],
        [-1,  0,  1],
        [-1,  1, -1]]])

函数where返回触发高级索引的整数数组元组:

In [1071]: idx = np.where((A==1)*(B==1))

In [1072]: idx
Out[1072]: 
(array([1, 1, 1, 2, 2, 2], dtype=int64),
 array([1, 1, 2, 0, 1, 2], dtype=int64),
 array([1, 2, 1, 1, 2, 1], dtype=int64))

In [1073]: A[idx]
Out[1073]: array([1, 1, 1, 1, 1, 1])

In [1074]: B[idx]
Out[1074]: array([1, 1, 1, 1, 1, 1])

发布这个问题可能有点仓促。 使用 numpy 的

logical_and(x1, x2[, out])

最后完美地完成了这项工作!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM