简体   繁体   中英

Reshaping a matrix in python numpy

I have the following matrix:

x = np.array([["a","b","c","d"], ["e","f","g","h"], ["i","j","k","l"], ["m","n","o","p"]])
[['a' 'b' 'c' 'd']
 ['e' 'f' 'g' 'h']
 ['i' 'j' 'k' 'l']
 ['m' 'n' 'o' 'p']]

How do I reshape to:

[['a' 'b' 'e' 'f']
 ['c' 'd' 'g' 'h']
 ['i' 'j' 'm' 'n']
 ['k' 'l' 'o' 'p']]

It tried

np.array([x.reshape(2,2) for x in x]).reshape(4,4)

but it just gives me the original matrix back.

You can use numpy.lib.stride_tricks.as_strided :

from numpy.lib.stride_tricks import as_strided
x = np.array([["a","b","c","d"], ["e","f","g","h"], ["i","j","k","l"], ["m","n","o","p"]])
y = as_strided(x, shape=(2, 2, 2, 2),
    strides=(8*x.itemsize, 2*x.itemsize, 4*x.itemsize,x.itemsize)
).reshape(x.shape).copy()

print(y)

Prints:

array([['a', 'b', 'e', 'f'],
       ['c', 'd', 'g', 'h'],
       ['i', 'j', 'm', 'n'],
       ['k', 'l', 'o', 'p']], dtype='<U1')

With as_strided we can make the original array into an array containing 4 2x2 blocks:

>>> as_strided(x, shape=(2, 2, 2, 2),
    strides=(8*x.itemsize, 2*x.itemsize, 4*x.itemsize,x.itemsize)
)

array([[[['a', 'b'],
         ['e', 'f']],

        [['c', 'd'],
         ['g', 'h']]],


       [[['i', 'j'],
         ['m', 'n']],

        [['k', 'l'],
         ['o', 'p']]]], dtype='<U1')

You can learn more about as_strided in detail, here

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