[英]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.