Skip to content Skip to sidebar Skip to footer

How To Understand Numpy's Combined Slicing And Indexing Example

I am trying to understand numpy's combined slicing and indexing concept, however I am not sure how to correctly get the below results from numpy's output (by hand so that we can un

Solution 1:

Whenever you use an array of indices, the result has the same shape as the indices; for example:

>>> x = np.ones(5)
>>> i = np.array([[0, 1], [1, 0]])
>>> x[i]
array([[ 1.,  1.],
       [ 1.,  1.]])

We've indexed with a 2x2 array, and the result is a 2x2 array. When combined with a slice, the size of the slice is preserved. For example:

>>> x = np.ones((5, 3))
>>> x[i, :].shape
(2, 2, 3)

Where the first example was a 2x2 array of items, this example is a 2x2 array of (length-3) rows.

The same is true when you switch the order of the slice:

>>> x = np.ones((5, 3))
>>> x[:, i].shape
(5, 2, 2)

This can be thought of as a list of five 2x2 arrays.

Just remember: when any dimension is indexed with a list or array, the result has the shape of the indices, not the shape of the input.


Solution 2:

a[:,j][0] is equivalent to a[0,j] or [0, 1, 2, 3][j] which gives you [[2, 1], [3, 3]])

a[:,j][1] is equivalent to a[1,j] or [4, 5, 6, 7][j] which gives you [[6, 5], [7, 7]])

a[:,j][2] is equivalent to a[2,j] or [8, 9, 10, 11][j] which gives you [[10, 9], [11, 11]])


Post a Comment for "How To Understand Numpy's Combined Slicing And Indexing Example"