python - 为什么 numpy.where 不适用于 'double' 切片数组?

标签 python arrays numpy

我不明白为什么“双”切片不适用于 where?

>>> t
array([False,  True,  True,  True], dtype=bool)
>>> np.where(t[:3])
(array([1, 2]),)

但是:

>>> np.where(t[1:3])
(array([0, 1]),)

最佳答案

这是预期的输出,因为 np.where 不知道您所分割的内容的完整上下文。首先看切片数组:

In [384]: t[:3]
Out[384]: array([False,  True,  True], dtype=bool)
        #        0       1      2

In [385]: np.where(t[:3])
Out[385]: (array([1, 2]),)

In [386]: t[1:3]
Out[386]: array([ True,  True], dtype=bool)
        #         0      1

In [387]: np.where(t[1:3])
Out[387]: (array([0, 1]),)

在第二个中,您将跳过第一个元素;您从 1 开始,但第一个元素是 0:

In [388]: t[0:3]
Out[388]: array([False,  True,  True], dtype=bool)
        #        0       1      2

In [389]: np.where(t[0:3])
Out[389]: (array([1, 2]),)
<小时/>

如果您想要原始数组中的索引,则必须按照 @BiRico 上面的建议进行一些数学运算(但要小心,首先从元组中获取第一个元素)

In [390]: n = 1

In [391]: np.where(t[n:3])[0] + n
Out[391]: array([1, 2])

关于python - 为什么 numpy.where 不适用于 'double' 切片数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18796253/

相关文章:

python - 使用 Python 获取一周中两天之间的日期

python - 如何通过访问数据框而不是python中的csv进行情感分析?

c - geeksforgeeks 的 k 最大元素练习

arrays - 二维数组作为 OpenCL 内核参数

python - numpy数组: IndexError: failed to coerce slice entry of type numpy. ndarray的多个索引到整数

python - 带条件的每行唯一值的二维矢量化

python - Python/C API 中 Python 胶囊的安全和防御编码视角

python - keras fit_generator 中 nb_epoch、samples_per_epoch 和 nb_val_samples 的标准?

javascript - 如何使用 javascript 从 php 脚本交互获取数据

python - 如何绘制 3D 曲面?