python - 使用索引的 Numpy 数组索引

标签 python python-3.x numpy

我写了以下内容:

arr3=np.array([[[1,2,3],[1,2,3],[1,2,3],[1,2,3]],[[2,2,3],[4,2,3],[4,2,2],[2,2,2]],[[1,1,1],[1,1,1],[1,1,1],[1,1,1]]])

如我所料,
arr3[0:3,1] 应返回与
相同的结果 arr3[0:3][1]:array([[2, 2, 3],[4, 2, 3],[4, 2, 2],[2, 2, 2]])

但它返回:array([[1, 2, 3],[4, 2, 3],[1, 1, 1]])

顺便说一句,我在 Jupyter notebook 中使用 python3

最佳答案

在做 arr3[0:3,1] 时, 你正在从 0:3 中获取元素在第一个axis然后对于每一个,取第一个 element .

这与采用 0:3 给出了不同的结果在第一个轴上有 arr3[0:3]然后取第一个 array来自这个axis .

所以在这种情况下,0:3在这两种情况下,部分都不执行任何操作,因为 array's形状是 (3, 4, 3)所以服用first 3只是给你同样的array .这在第二种情况下绝对没有任何作用,但在第一种情况下,它确实充当了一个占位符,因此您可以访问第二个 axis。 , 但为此你应该只使用冒号:[:, some_index] .

看看怎么一样array

>>> arr3[0:3]
array([[[1, 2, 3],
        [1, 2, 3],
        [1, 2, 3],
        [1, 2, 3]],

       [[2, 2, 3],
        [4, 2, 3],
        [4, 2, 2],
        [2, 2, 2]],

       [[1, 1, 1],
        [1, 1, 1],
        [1, 1, 1],
        [1, 1, 1]]])

但是当你做 arr3[:, 1]你正在从 second axis 中获取第二个元素的 array这样会给你:

array([[1, 2, 3],
       [4, 2, 3],
       [1, 1, 1]])

而在另一种情况下,您要从第一个 axis 中获取第二个元素。数组的`所以:

array([[2, 2, 3],
       [4, 2, 3],
       [4, 2, 2],
       [2, 2, 2]])

进一步阅读 numpy indexing ,看看 this page on scipy .

记下直接适用于您的问题的具体描述:

When there is at least one slice (:), ellipsis (...) or np.newaxis in the index (or the array has more dimensions than there are advanced indexes), then the behaviour can be more complicated. It is like concatenating the indexing result for each advanced index element

关于python - 使用索引的 Numpy 数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47363894/

相关文章:

python - 使用 numpy.genfromtxt 在 Python 3 中加载 UTF-8 文件

python - 如何在 django 表单中设置自定义 HTML 属性?

python - pandas 中带有内部连接的 where 条件

python - 如何处理TypeError : Object of type 'bytes' is not JSON serializable?

python - Python中的多个字符串替换

python - 在 python/pandas 中连接文本和数字

python - 在 PyQt4 中打开文件时出现 "Cancel"错误

Python Selenium - 高亮元素不做任何事情

python - 如何从Linux日志文件中只获取新行?

python - 嵌套数组的最小值(可能部分为空)