3

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, except the first you combine the rows into a new matrix?

For example:

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

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

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

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

2 Answers 2

4

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_.

Sign up to request clarification or add additional context in comments.

4 Comments

Neat! Indexing a 2D array with another 2D array bends my mind a little.
Would this also be possible with np.r_ ?
@Alex Well we are dealing with 2D indexing array. We use np.r_ to form 1D arrays. So, I am not sure if/how we could use that in here.
My mistake, did not read the fine print in the documentation.
1

My approach would be a list comprehension:

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

1 Comment

I suppose I'd call this pythonic, but Divakar's answer is definitely more numpythonic.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.