繁体   English   中英

在 python numpy 中重塑矩阵

[英]Reshaping a matrix in python numpy

我有以下矩阵:

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']]

我如何重塑:

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

它试过了

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

但它只是给了我原来的矩阵。

您可以使用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)

印刷:

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

使用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')

您可以在此处详细了解as_strided

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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