【问题标题】:Logical indexing in python for nd arrayspython中用于nd数组的逻辑索引
【发布时间】:2016-04-25 11:40:09
【问题描述】:

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

我正在尝试:

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

但得到一个错误:

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

我该如何解决这个问题?

【问题讨论】:

  • 可能有点草率地发布这个问题。使用 numpy 的logical_and(x1, x2[, out])

标签: python arrays numpy


【解决方案1】:

Numpy 不能重载“and”关键字。但是,它为此重载了二进制 AND 运算符 &。试试:

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

括号很重要。我发现它经常(并不总是)比logical_and更具可读性

【讨论】:

  • 谢谢!我还发现 numpy 有自己的一组逻辑函数(如下所示),但这非常有用!
【解决方案2】:

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返回一个触发advanced indexing的整数数组元组:

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])

【讨论】:

    【解决方案3】:

    也许有点草率地发布这个问题。用过 numpy 的

    logical_and(x1, x2[, out])
    

    到底哪个做得很完美!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-28
      • 2014-08-23
      • 1970-01-01
      • 1970-01-01
      • 2014-11-05
      • 2014-01-25
      • 2021-03-29
      • 2015-06-06
      相关资源
      最近更新 更多