python - 检查索引处 numpy 数组的值

标签 python arrays numpy indexing

我最近开始使用 numpy 工作。我正在尝试测试二维数组是否包含特定的子数组。下面的代码返回一个错误。我该如何解决这个问题?

import numpy as np

testArray = np.array([[None, 0], [None, 0], [None, 0], [None, 0], [None, 0], [None, 0], [None, 0], [None, 0], [None, 0]])

for i in range(len(testArray)):
    if (testArray[i] == [None, 0]):
        print(i)

最佳答案

无需迭代,您可以使用全部:

>>> testArray[(testArray == [None,0]).all(1)]
array([[None, 0],
       [None, 0],
       [None, 0],
       [None, 0],
       [None, 0],
       [None, 0],
       [None, 0],
       [None, 0]], dtype=object)

或者,如果您只想查看该子数组是否存在,请另外使用any:

>>> (testArray == [None,0]).all(1).any()
True

关于python - 检查索引处 numpy 数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53712730/

相关文章:

python - Pygame 在 Windows 10 上使用 pip install pygame 失败

arrays - 在 Swift 中, append 数组的效率如何?

python - NumPy:计算数组中某些元素的平均值

python - 在 Python 2.7 中创建 (a,b) 点的 X × Y 维数组

python - 将字符串转换为日期时间 [hh :mm:ss]

python - 具有加州住房数据的神经网络

python ctype 字符串指针 32b 与 64b : segmentation fault (core dumped)

javascript - 如何使用单个删除从对象中删除多个属性?

c++ - 如何在数组 C++ 中存储未知数量的元素

python - 为什么不使用 Scipy 的 FFT 代码结果与 Scipy FFT 不相似?