python - numpy 3 维数组中间索引错误

标签 python arrays numpy

当我使用带有 numpy 模块的 python 2.7 时,我似乎发现了一个错误:

import numpy as np
x=np.arange(3*4*5).reshape(3,4,5)
x

这里我得到了完整的 'x' 数组,如下所示:

array([[[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9],
        [10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19]],

       [[20, 21, 22, 23, 24],
        [25, 26, 27, 28, 29],
        [30, 31, 32, 33, 34],
        [35, 36, 37, 38, 39]],

       [[40, 41, 42, 43, 44],
        [45, 46, 47, 48, 49],
        [50, 51, 52, 53, 54],
        [55, 56, 57, 58, 59]]])

然后我尝试索引工作表 [1] 中的单行值:

x[1][0][:]

结果:

array([20, 21, 22, 23, 24])

但是当我尝试索引工作表 [1] 中的单个列时出了点问题:

x[1][:][0]

结果还是和之前一样:

array([20, 21, 22, 23, 24])

应该是array([20, 25, 30, 35])吗??

用范围索引中间索引时似乎有问题?

最佳答案

不,这不是错误。

当您使用 [:] 时,您使用的是切片符号,它会占用所有列表:

l = ["a", "b", "c"]
l[:]
#output:
["a", "b", "c"]

在你的情况下:

x[1][:]
#output:
array([[20, 21, 22, 23, 24],
       [25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34],
       [35, 36, 37, 38, 39]])

您真正希望的是使用 numpy indexing 表示法:

x[1, : ,0]
#output:
array([20, 25, 30, 35])

关于python - numpy 3 维数组中间索引错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39200644/

相关文章:

python - 如何在 Linux 中配置 sys.path 变量?

php - 在 1 个下拉条目中显示 2 个数组值

javascript - Linq.js 子查询

python - Decimal 类型 NumPy 的矩阵逆

python - 大型数组的插值和外插

python - 使用 python 3.5 在 centos 6.5 上安装 tkinter

python - 递归使用Scrapy从网站上抓取网页

c++ - 复制指针数组并跳过某些索引

python - 值错误 : operands could not be broadcast together with shapes (7, ) (6,) (7,)

python - pymongo 和 $ne : null 的语法错误