[英]In Python, is it possible to return multiple 3D array slices all at once without a for loop?
Here is example code.这是示例代码。 I want to find the way to run the last two lines at once and return the results in the same array all at once without concatenation, is this possible?我想找到一次运行最后两行的方法,并在不连接的情况下一次将结果全部返回到同一个数组中,这可能吗?
import numpy as np
arr = np.ones((3,3,3))
arr[0:2,0:2,0:2]
arr[1:3,1:3,1:3]
The resulting command should be like结果命令应该是这样的
arr[(0:1,2:3),(0:1,2:3),(0:1,2:3)]
And the dimensionality of the results will be (2,2,2,2).结果的维度将为 (2,2,2,2)。
Your array and slices:您的数组和切片:
In [128]: arr = np.arange(27).reshape(3,3,3)
In [129]: a1=arr[0:2,0:2,0:2]
...: a2=arr[1:3,1:3,1:3]
In [130]: a1.shape
Out[130]: (2, 2, 2)
In [131]: a2.shape
Out[131]: (2, 2, 2)
a1
and a2
are views
, sharing the databuffer with arr
. a1
和a2
是views
,与arr
共享数据缓冲区。
Joining them on a new dimension ( np.stack
will also do this):在一个新的维度上加入他们( np.stack
也会这样做):
In [132]: a3 = np.array((a1,a2))
In [133]: a3.shape
Out[133]: (2, 2, 2, 2)
In [134]: a3
Out[134]:
array([[[[ 0, 1],
[ 3, 4]],
[[ 9, 10],
[12, 13]]],
[[[13, 14],
[16, 17]],
[[22, 23],
[25, 26]]]])
Notice how the flattened values are not contiguous (or other regular pattern).请注意展平值是如何不连续的(或其他规则模式)。 So they have to a copy of some sort:所以他们必须要某种副本:
In [135]: a3.ravel()
Out[135]: array([ 0, 1, 3, 4, 9, 10, 12, 13, 13, 14, 16, 17, 22, 23, 25, 26])
An alternative is to construct the indices, join them, and then do one indexing.另一种方法是构建索引,加入它们,然后进行一次索引。 That times about the same.那次差不多。 And in this case I think that would be more complicated.在这种情况下,我认为会更复杂。
=== ===
Another way with stride_tricks. stride_tricks 的另一种方式。 I won't promise anything about speed.我不会 promise 关于速度的任何事情。
In [147]: x = np.lib.stride_tricks.sliding_window_view(arr,(2,2,2))
In [148]: x.shape
Out[148]: (2, 2, 2, 2, 2, 2)
In [149]: x[0,0,0]
Out[149]:
array([[[ 0, 1],
[ 3, 4]],
[[ 9, 10],
[12, 13]]])
In [150]: x[1,1,1]
Out[150]:
array([[[13, 14],
[16, 17]],
[[22, 23],
[25, 26]]])
In [151]: x[[0,1],[0,1],[0,1]]
Out[151]:
array([[[[ 0, 1],
[ 3, 4]],
[[ 9, 10],
[12, 13]]],
[[[13, 14],
[16, 17]],
[[22, 23],
[25, 26]]]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.