Skip to content Skip to sidebar Skip to footer

Is Not It Possible To Patch The 2d Array Into Array Of Subarry Using Functions Available In Numpy?

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

Solution 1:

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.

Solution 2:

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.

Post a Comment for "Is Not It Possible To Patch The 2d Array Into Array Of Subarry Using Functions Available In Numpy?"