如何切割numpy数组,使每个切片成为一个新数组

时间:2017-09-08 12:16:14

标签: python numpy

说有这个数组:

x=np.arange(10).reshape(5,2)
x=array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7],
       [8, 9]])

可以对数组进行切片,以便对于每一行,除了第一行之外,您将行组合成一个新矩阵吗?

例如:

newMatrixArray[0]=array([[0, 1],
       [2, 3]])

newMatrixArray[1]=array([[0, 1],
       [4, 5]])

newMatrixArray[2]=array([[0, 1],
       [6, 7]])

使用for循环这很容易,但有没有pythonic方法呢?

2 个答案:

答案 0 :(得分:4)

我们可以形成所有那些行索引,然后简单地索引到x

因此,一个解决方案是 -

n = x.shape[0]
idx = np.c_[np.zeros((n-1,1),dtype=int), np.arange(1,n)]
out = x[idx]

示例输入,输出 -

In [41]: x
Out[41]: 
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7],
       [8, 9]])

In [42]: out
Out[42]: 
array([[[0, 1],
        [2, 3]],

       [[0, 1],
        [4, 5]],

       [[0, 1],
        [6, 7]],

       [[0, 1],
        [8, 9]]])

还有其他各种方法来获取这些指数idx。我们只是为了好玩而提出一些建议。

一个broadcasting -

(np.arange(n-1)[:,None] + [0,1])*[0,1]

一个array-initialization -

idx = np.zeros((n-1,2),dtype=int)
idx[:,1] = np.arange(1,n)

一个cumsum -

np.repeat(np.arange(2)[None],n-1,axis=0).cumsum(0)

一个 list-expansion -

np.c_[[[0]]*(n-1), range(1,n)]

另外,为了提高效果,请使用np.column_stacknp.concatenate代替np.c_

答案 1 :(得分:1)

我的方法是列表理解:

np.array([
    [x[0], x[i]]
    for i in range(1, len(x))
])
相关问题