I currently looking for method in which i can split a ndarray into smaller ndarrays.
example: given ndarray with shape (78,1440,3), from which i want to extract a list of smaller ndarrays of the size (78,72,3), that would be 20 smaller sub ndarrays.
I tried using numpy.split
.
numpy.split(matrix,72,axis=1)
which generates a list of length 72 and the first entry has the shape (78,20,3)..
Why am I not able to extract the size i need?
The 72 in the split
is the number of elements to split it into, not the size of the splitted dimensions (according to the axis).
You can however use:
numpy.split(matrix,,axis=1)
to split it into 20 elements of length 72 (for your given case). Note that you have to ensure that the shape[1]
is dividable by 72 otherwise a ValueError
will be raised.
Approach #1 : You can use np.hsplit
made exactly for this task -
np.hsplit(arr,20) # creates list of 20 arrays
Sample run -
1) Input array :
In [52]: a = np.random.randint(0,9,(2,6,3))
In [53]: a
Out[53]:
array([[[7, 8, 8],
[7, 7, 1],
[1, 6, 4],
[6, 3, 8],
[4, 7, 4],
[0, 6, 3]],
[[0, 8, 5],
[2, 2, 8],
[6, 0, 7],
[5, 4, 6],
[4, 3, 1],
[8, 6, 6]]])
2) Split axis=1 into 3
parts , thus each part/subarray would be of length (2,2,3)
shape. Thus, we would get a list of those 3 arrays :
In [54]: b = np.hsplit(a,3)
3) Manually verify those parts :
In [55]: b[0]
Out[55]:
array([[[7, 8, 8],
[7, 7, 1]],
[[0, 8, 5],
[2, 2, 8]]])
In [56]: b[1]
Out[56]:
array([[[1, 6, 4],
[6, 3, 8]],
[[6, 0, 7],
[5, 4, 6]]])
In [57]: b[2]
Out[57]:
array([[[4, 7, 4],
[0, 6, 3]],
[[4, 3, 1],
[8, 6, 6]]])
Approach #2 : Another tool for this task would be np.array_split
-
np.array_split(arr,20,axis=1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.