首页 > 解决方案 > 在 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)

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

标签: pythonnumpy

解决方案


您可以使用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原始数组变成一个包含 42x2个块的数组:

>>> 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详细了解更多信息


推荐阅读