简体   繁体   English

如何切割和扩展2D numpy数组?

[英]How to slice and extend a 2D numpy array?

I have a numpy array of size nxm . 我有一个大小为nxm的numpy数组。 I want the number of columns to be limited to k and rest of the columns to be extended in new rows. 我希望将列数限制为k ,将其余列扩展为新行。 Following is the scenario - 以下是情景 -

Initial array: nxm 初始数组: nxm

Final array: pxk 最终数组: pxk

where p = (m/k)*n 其中p = (m/k)*n

Eg. 例如。 n = 2, m = 6, k = 2

Initial array: 初始数组:

[[1, 2, 3, 4, 5, 6,],
[7, 8, 9, 10, 11, 12]]

Final array: 最终阵列:

[[1, 2],
[7, 8],
[3, 4],
[9, 10],
[5, 6],
[11, 12]]

I tried using reshape but not getting the desired result. 我尝试使用reshape但没有得到所需的结果。

Here's one way to do it 这是一种方法

q=array([[1, 2, 3, 4, 5, 6,],
         [7, 8, 9, 10, 11, 12]])
r=q.T.reshape(-1,2,2)
s=r.swapaxes(1,2)
t=s.reshape(-1,2)

as a one liner, 作为一个班轮,

q.T.reshape(-1,2,2).swapaxes(1,2).reshape(-1,2)

array([[ 1,  2],
       [ 7,  8],
       [ 3,  4],
       [ 9, 10],
       [ 5,  6],
       [11, 12]])

EDIT: for the general case, use 编辑:对于一般情况,使用

q=arange(1,1+n*m).reshape(n,m) #example input
r=q.T.reshape(-1,k,n)
s=r.swapaxes(1,2)
t=s.reshape(-1,k)

one liner is: 一个班轮是:

q.T.reshape(-1,k,n).swapaxes(1,2).reshape(-1,k)

example for n=3,m=12,k=4 n=3,m=12,k=4例子n=3,m=12,k=4

q=array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12],
         [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
         [25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]])

result is 结果是

array([[ 1,  2,  3,  4],
       [13, 14, 15, 16],
       [25, 26, 27, 28],
       [ 5,  6,  7,  8],
       [17, 18, 19, 20],
       [29, 30, 31, 32],
       [ 9, 10, 11, 12],
       [21, 22, 23, 24],
       [33, 34, 35, 36]])

Using numpy.vstack and numpy.hsplit : 使用numpy.vstacknumpy.hsplit

a = np.array([[1, 2, 3, 4, 5, 6,],
              [7, 8, 9, 10, 11, 12]])
n, m, k = 2, 6, 2
np.vstack(np.hsplit(a, m/k))

result array: 结果数组:

array([[ 1,  2],
       [ 7,  8],
       [ 3,  4],
       [ 9, 10],
       [ 5,  6],
       [11, 12]])

UPDATE As flebool commented , above code is very slow, because hsplit returns a python list, and then vstack reconstructs the final array from a list of arrays. 更新正如flebool评论的那样 ,上面的代码非常慢,因为hsplit返回一个python列表,然后vstack从一个数组列表重建最终的数组。

Here's alternative solution that is much faster. 这是替代解决方案,速度更快。

a.reshape(-1, m/k, k).transpose(1, 0, 2).reshape(-1, k)

or 要么

a.reshape(-1, m/k, k).swapaxes(0, 1).reshape(-1, k)

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

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