2

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.

AyeTown
  • 831
  • 1
  • 5
  • 20

1 Answers1

0

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

Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52