NumPy Slicing and Indexing Exercise

Q1 Consider the following NumPy array

import numpy
X = numpy.array([
  [11 ,22, 33], 
  [44, 55, 66], 
  [77, 88, 99]])

Return the array of elements in the third column (from all rows).

Solution

In the row portion, we will write ":". And in the column portion, we will write 2 because the third column's index position is 2.

X[:, 2]

Q2 Consider the following NumPy array

import numpy
Y = numpy.array([
  [3,6,9,12], 
  [15,18,21,24], 
  [27,30,33,36], 
  [39,42,45,48],
  [51,54,57,60]
  ])

Return a sub-array consisting of the odd rows and even columns of y

Solution

As we want odd rows so we will write 2 in step porition of row indexing.

For even columns, we will start with the second column, whose index value is 1, and in the step portion, we will write 2.

Y[::2, 1::2]

Recommended Posts