python - 如何使用Python在数组的所有第三列中找到精确值?

标签 python arrays numpy

如果我有一个像这样的 Numpy 数组:

array([0, 0, 0]
      [0, 0, 1]
      [0, 1, 2]
      [0, 1, 3]
      [1, 0, 4]
      [1, 0, 5]
      [1, 1, 6]
      [1, 1, 7])

我尝试使用

if c==1 in range(X[:,2]):
  print 'yes'

但出现错误

TypeError: only length-1 arrays can be converted to Python scalars

是否可以使用切片和 if 语句找到 c==1

最佳答案

因为 x[:,2] 为您提供了第三列中的元素数组

>>> import numpy as np
>>> x = np.array([[0, 0, 0], [0, 0, 1], [0, 1, 2], [0, 1, 3], [1, 0, 4], [1, 0, 5], [1, 1, 6], [1, 1, 7]])
>>> x
array([[0, 0, 0],
       [0, 0, 1],
       [0, 1, 2],
       [0, 1, 3],
       [1, 0, 4],
       [1, 0, 5],
       [1, 1, 6],
       [1, 1, 7]])
>>> x[:,2]
array([0, 1, 2, 3, 4, 5, 6, 7])
>>> if 1 in x[:,2]:
...     print("yes")
... 
yes

这样效率最高

>>> if np.any(x[:, 2] == 1):
...     print("yes")
... 
yes
>>> 

关于python - 如何使用Python在数组的所有第三列中找到精确值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27960347/

相关文章:

python - Python 中的每类常量

c++ - Qt 字符指针数组

python - 如何使用 h5py 更新二维数组?

c - 数组下标的无效类型 int[int]

python - 是什么导致 Python 提示在没有列表的代码中列出列表?

python - scipy中fmin_cg的梯度函数

javascript - 用javascript或python镜像的html

python - 将 json 数据转换为数据框

python - 是什么让尝试: exit early?

php - 如何检查多维数组是否为空?