简体   繁体   中英

1d numpy array to blocks in a matrix

I have a 1D array that I need to reshape() into a 2D array, but the reshape is tricky because it seems like some kind of grouping is needed.

I have tried a few different series of reshape() and transpose() combinations, but I have not landed on the correct arrangement of values.

I have provided two arrays below. I would like to reshape the 1D array a to have the same shape as the 2D array b . What makes this trick is that I want the 4 ones in the middle. I made some attempts to make 2x2 blocks for every 4 values then arrange into the 6x6 array, but I did not have success.

a = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

b = np.array([
    [0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0],
    [0, 0, 1, 1, 0, 0],
    [0, 0, 1, 1, 0, 0],
    [0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0]])

Here are the shapes

> a.shape                                                                          
(36,)                                                                                
> b.shape                                                                          
(6, 6)   

This does it:

In [327]: a = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0,
     ...:  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
     ...: 
In [328]: a.reshape(3,3,2,2)
Out[328]: 
array([[[[0, 0],
         [0, 0]],

        [[0, 0],
         [0, 0]],

        [[0, 0],
         [0, 0]]],


       [[[0, 0],
         [0, 0]],

        [[1, 1],
         [1, 1]],

        [[0, 0],
         [0, 0]]],


       [[[0, 0],
         [0, 0]],

        [[0, 0],
         [0, 0]],

        [[0, 0],
         [0, 0]]]])

the (2,2) block of 1s is visible, but I need to switch the middle 2 dimensions:

In [329]: a.reshape(3,3,2,2).transpose(0,2,1,3)
Out[329]: 
array([[[[0, 0],
         [0, 0],
         [0, 0]],

        [[0, 0],
         [0, 0],
         [0, 0]]],


       [[[0, 0],
         [1, 1],
         [0, 0]],

        [[0, 0],
         [1, 1],
         [0, 0]]],


       [[[0, 0],
         [0, 0],
         [0, 0]],

        [[0, 0],
         [0, 0],
         [0, 0]]]])

now back to 2d:

In [330]: a.reshape(3,3,2,2).transpose(0,2,1,3).reshape(6,6)
Out[330]: 
array([[0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 1, 1, 0, 0],
       [0, 0, 1, 1, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0]])

The basic steps of reshape, transpose, followed by reshape is common to this kind of problem. The transpose details very.

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.

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