Python 根据条件获取数组索引位置

Python 根据条件获取数组索引位置,python,numpy,Python,Numpy,我有一个大的numpy数组,我想根据给定的条件获取数组索引。Numpy提供此选项,但返回布尔数组: >>> import numpy as np >>> a = np.arrary([1, 2, 3, 4, 1, 2, 3] >>> b = a == 3 >>> b array([False, False, True, False, False, False, True]) 但是我真的想把实际的索引位置作为整数,有没有比这

我有一个大的numpy数组,我想根据给定的条件获取数组索引。Numpy提供此选项,但返回布尔数组:

>>> import numpy as np
>>> a = np.arrary([1, 2, 3, 4, 1, 2, 3]
>>> b = a == 3
>>> b
array([False, False, True, False, False, False, True])
但是我真的想把实际的索引位置作为整数,有没有比这个更简单的方法呢

>>> c = np.arange(len(b))
>>> c = c[b]
>>> c
array([2,6])

换句话说,有没有一种方法可以在不创建上述c数组的情况下执行此操作?

我相信您正在寻找:


我相信您正在寻找:

我会选择:

import numpy as np
a = np.array([1, 2, 3, 4, 1, 2, 3])
indices, = np.where(a==3)
print indices
# [2 6]
允许更轻松地处理n-dim阵列的错误(即,如果要解压缩的项目太多,将引发异常),并且不需要展平。

我选择:

import numpy as np
a = np.array([1, 2, 3, 4, 1, 2, 3])
indices, = np.where(a==3)
print indices
# [2 6]

允许更轻松地处理n-dim阵列的错误(即,如果要解包的项目太多,将引发异常),并且不需要展平。

我建议使用简单的
np.where
。我建议使用简单的
np.where