numpy中的区块重塑?

2024-04-20 14:01:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个以块为单位的列的numpy数组。我想把积木转位。这在概念上很简单,我想一个人可以做得很简单,但我不知道怎么做。你知道吗

给定块形式np.hstack(list_of_blocks)的numpy数组,我想得到np.vstack(list_of_blocks)。你知道吗

为了更精确,我想在下面的代码片段中从数组a转到数组b。你知道吗

import numpy as np
a = np.zeros((3,6))
b = np.zeros((9,2))
t_max = 3
for col in range(1,7):
    for time in range(1,t_max+1):    
        val = ((1+col)//2)*100+((col+1) % 2)*10+time
        a[time-1,col-1]= val
        b[time+t_max*(((1+col)//2)-1)-1,((col+1) % 2)] = val

矩阵看起来像:

>>> print(a)
[[101. 111. 201. 211. 301. 311.]
 [102. 112. 202. 212. 302. 312.]
 [103. 113. 203. 213. 303. 313.]]

>>> print(b)
[[101. 111.]
 [102. 112.]
 [103. 113.]
 [201. 211.]
 [202. 212.]
 [203. 213.]
 [301. 311.]
 [302. 312.]
 [303. 313.]]

当然,矩阵不是3 x (2*3),而是n x (k*m)

在numpy,什么是一种有效的重塑方式?你知道吗


Tags: ofinnumpyfortimenpzerosrange
2条回答

np.vstack(np.hsplit(a,3))做的正是所要求的,可读性强,但性能不如Divkar的答案。你知道吗

重塑,排列轴和重塑-

N = a.shape[1]//t_max
b_out = a.reshape(a.shape[0],-1,N).swapaxes(0,1).reshape(-1,N)

有关^{}的详细信息。你知道吗

相关问题 更多 >