Skip to content Skip to sidebar Skip to footer

How To Slice Numpy Array Such That Each Slice Becomes A New Array

Say there is this array: 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,

Solution 1:

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]

Sample input, output -

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]]])

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

One with broadcasting -

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

One with array-initialization -

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

One with cumsum -

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

One with list-expansion -

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

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

Solution 2:

My approach would be a list comprehension:

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

Post a Comment for "How To Slice Numpy Array Such That Each Slice Becomes A New Array"