如何切片numpy数组,使每个切片成为一个新数组 [英] How to slice numpy array such that each slice becomes a new array

查看:103
本文介绍了如何切片numpy数组,使每个切片成为一个新数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说有这个数组:

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

是否可以对数组进行切片,以便除第一行外,将每一行都组合成一个新的矩阵?

Can the array be sliced such that for each row, except the first you combine the rows into a new matrix?

例如:

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

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

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

使用for循环很容易做到这一点,但是有Python的方式可以做到这一点吗?

This would be easy to do with a for loop, but is there a pythonic way of doing it?

推荐答案

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

We could form all those row indices and then simply index into x.

因此,一种解决方案是-

Thus, one solution would be -

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.让我们提出一些只是为了好玩的事.


There are various other ways to get those indices idx. Let's propose few just for fun-sake.

一个与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_.

Also, for performance, use np.column_stack or np.concatenate in place of np.c_.

这篇关于如何切片numpy数组,使每个切片成为一个新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆