简体   繁体   English

在2D numpy数组中使用3D样式切片

[英]Using 3D style slicing in a 2D numpy array

I have a function that takes a numpy array (A) as input. 我有一个函数,需要一个numpy数组(A)作为输入。 This array could be a 2d or a 3d array depending on a mathematical calculation. 根据数学计算,此数组可以是2d或3d数组。 There is an integer m which could be any number, except when the array is 2D, the value of m will always be 0. I want to pass a silce of A to another function. 有一个整数m,该整数可以是任意数字,但当数组为2D时,m的值将始终为0。我想将A的silc传递给另一个函数。 Since A can be both 3D or 2D, I tried 3D style slicing. 由于A可以是3D或2D,因此我尝试了3D样式切片。

def fun(A):
    ... some code
    ans = fun2(A[:,:,m]) #The value of m is 0 if A is 2D

This gives me an IndexError when A is 2D 当A为2D时,这给我一个IndexError

IndexError: too many indices for array

I want to pass the full 2D array to fun2 if A is 2D, like it happens in MATLAB. 如果A是2D,我想将完整的2D数组传递给fun2,就像在MATLAB中一样。 How can it be done in Python? 如何在Python中完成? I use Python 2. 我使用Python 2。

Seems like a good setup to use np.atleast_3d as we can force it to be 3D and then simply slice the m-th index along the last axis, like so - 似乎是使用np.atleast_3d的好设置,因为我们可以将其强制3D ,然后简单地沿最后一个轴切片第m个索引,如下所示-

np.atleast_3d(A)[...,m] # Or np.atleast_3d(A)[:,:,m]

It's still a view into the array, so no efficiency lost there! 它仍然是阵列的视图,因此不会损失任何效率!

Case runs 案例运行

1) 2D : 1)2D:

In [160]: A = np.random.randint(11,99,(4,5))

In [161]: np.atleast_3d(A)[...,0]
Out[161]: 
array([[13, 84, 38, 15, 26],
       [64, 91, 29, 11, 48],
       [25, 66, 77, 14, 87],
       [59, 96, 98, 30, 88]])

In [162]: A
Out[162]: 
array([[13, 84, 38, 15, 26],
       [64, 91, 29, 11, 48],
       [25, 66, 77, 14, 87],
       [59, 96, 98, 30, 88]])

2) 3D : 2)3D:

In [163]: A = np.random.randint(11,99,(4,3,5))

In [164]: np.atleast_3d(A)[...,1]
Out[164]: 
array([[34, 81, 66],
       [56, 20, 25],
       [45, 36, 64],
       [82, 64, 31]])

In [165]: A[:,:,1]
Out[165]: 
array([[34, 81, 66],
       [56, 20, 25],
       [45, 36, 64],
       [82, 64, 31]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM