[英]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
:您可以使用
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
我们可以将原始数组变成一个包含 4 个2x2
块的数组:
>>> 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您可以在此处详细了解
as_strided
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.