Is not it possible to patch the 2d array into array of subarry using functions available in numpy?

StackOverflow https://stackoverflow.com/questions/23546931

  •  18-07-2023
  •  | 
  •  

Question

Is not it possible to patch the 2d array into array of subarry using np.reshape and np.split functions?

import numpy as np
data = np.arange(24).reshape(4,6)
print data
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]
 [12 13 14 15 16 17]
 [18 19 20 21 22 23]]

answer = np.split(data,(-1,2,2),axis=1)

Expected answer is:

answer = [[[ 0  1]
   [ 6  7]]

  [[ 2  3]
   [ 8  9]]

  [[ 4  5]
   [10 11]]    

 [[12 13]
   [18 19]]

  [[14 15]
   [20 21]]

  [[16 17]
   [22 23]]]
Was it helpful?

Solution 2

You could also do the following:

>>> data = np.arange(24).reshape(4,6)
>>> data_split = data.reshape(2, 2, 3, 2)
>>> data_split = np.transpose(data_split, (0, 2, 1, 3))
>>> data_split = data_split.reshape(-1, 2, 2) # this makes a copy
>>> data_split
array([[[ 0,  1],
        [ 6,  7]],

       [[ 2,  3],
        [ 8,  9]],

       [[ 4,  5],
        [10, 11]],

       [[12, 13],
        [18, 19]],

       [[14, 15],
        [20, 21]],

       [[16, 17],
        [22, 23]]])

If you really want to call split on this array, it should be pretty straightforward to do, but this reordered array will behave as the tuple returned by split in most settings.

OTHER TIPS

split can't be used with multiple axis at once. But here is a solution using this operation twice:

In [1]: import numpy as np

In [2]: data = np.arange(24).reshape(4,6)

In [3]: chunk = 2, 2

In [4]: tmp = np.array(np.split(data, data.shape[1]/chunk[1], axis=1))

In [5]: answer = np.vstack(np.split(tmp, tmp.shape[1]/chunk[0], axis=1))

In [6]: answer
Out[6]: 
array([[[ 0,  1],
        [ 6,  7]],

       [[ 2,  3],
        [ 8,  9]],

       [[ 4,  5],
        [10, 11]],

       [[12, 13],
        [18, 19]],

       [[14, 15],
        [20, 21]],

       [[16, 17],
        [22, 23]]])

However I prefer the blockshaped solution as noticed by Cyber.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top