python - 任意维度的numpy数组切片

标签 python numpy dimension

假设我创建了一个任意维度 (n) 的数组。

#assign the dimension

>>> n=22

#create the numpy array

>>> TheArray=zeros([2]*n)

>>> shape(TheArray)

(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)

使用一些代码(在此示例中跳过)来填充数组的值。

现在,尝试访问数组的一些值

>>> TheArray[0:2,0:2,0:2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

array([[[ 0.,  0.],
        [ 0.,  0.]],

       [[ 0.,  0.],
        [ 0.,  0.]]])

如何制作 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 泛化到 n 的部分语法?

最佳答案

一种方法是使用 numpy.s_ :

In [55]: m = arange(2**6).reshape([2]*6)

In [56]: m.shape
Out[56]: (2, 2, 2, 2, 2, 2)

In [57]: m[:2,:2,:2,0,0,0]
Out[57]: 
array([[[ 0,  8],
        [16, 24]],

       [[32, 40],
        [48, 56]]])

In [58]: m[s_[:2, :2, :2] + (0,)*(n-3)]
Out[58]: 
array([[[ 0,  8],
        [16, 24]],

       [[32, 40],
        [48, 56]]])

我猜你可以去掉硬编码的 -3..

In [69]: m[(s_[:2, :2, :2] + (0,)*m.ndim)[:m.ndim]]
Out[69]: 
array([[[ 0,  8],
        [16, 24]],

       [[32, 40],
        [48, 56]]])

但老实说,如果需要的话,我可能会把它包装在一个函数中。

关于python - 任意维度的numpy数组切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12903367/

相关文章:

python - 如何修复编译器错误: cannot convert to a pointer type with Cython + numpy?

python - 使用 matplotlib 轴自动缩放而不绘制任何内容

python - 计算每 X 行的平均值

html - 为什么宽度为 : 100% is not assuming the full window width size?

arrays - 如何遍历 n 个维度?

python - .NET Core 2.0 和 Angular 初始应用程序构建失败 - 找不到 python 后跟 JavaScript 运行时错误

python - 如何在一个矩阵中连接多个向量(每个向量是新矩阵的一列)

使用 Numpy 进行类似 MATLAB 的数组索引

python - 有没有一种快速的方法来分段打乱 numpy 图像?

Java如何使JFrames最大化但不可调整大小