Flash Sale: Flat 70% + Addl. 25% Off on all Courses | Use Coupon DS25 in Checkout | Offer Expires In

  Enroll Now

Numpy - Arrays - Multi-Dimensional Arrays and Boolean Indexing

Multi-Dimensional NumPy Array

For multi-dimensional NumPy arrays, you can access the elements as below:

for a NumPy array multi_arr, you can use below syntax:

multi_arr[1, 2]      -  to access value at row 1 and column 2
multi_arr[1, :]      -  to access value at row 1 and all columns
multi_arr[:, 1]      -  to access value at all rows and column 1

multi_arr[3:7, 2:10] - to access values at row numbers from 3 to 7 (row index 3 to 6) and at column numbers from 2 to 10 (column index 2 to 9)

Syntax used is

array[ row_start_index : row_end_index, column_start_index : column_end_index]

Boolean Indexing

We can also index NumPy arrays using a NumPy array of boolean values on one axis to specify the indices that we want to access.

multi_arr = np.arange(12).reshape(3,4)

This will create a NumPy array of size 3x4 (3 rows and 4 columns) with values from 0 to 11 (value 12 not included).

print(multi_arr)

This will output

array( [ [ 0, 1, 2, 3], 
         [ 4, 5, 6, 7],
         [ 8, 9, 10, 11] ] )

rows_wanted = np.array( [True, False, True] )

Here, we are saying that we want first row (True) and the 3rd row (True) values, and we don't want 2nd-row value (False).

Let us use this boolean NumPy array rows_wanted in the above multi-dimensional array (multi_arr), to extract the desired portion of this multi_arr array.

multi_arr_portion = multi_arr[rows_wanted, : ]

Here, we are saying - get all columns :, but get only row numbers 1 and 3 ('0' and '2' index rows)

print(multi_arr_portion)

This will print

array( [ [ 0, 1, 2, 3],
         [ 8, 9, 10, 11] ] )
INSTRUCTIONS

Please follow the below steps:

(1) Import numpy as np

(2) Create a 4x5 (4 rows, 5 columns) NumPy array called my_multi_arr

my_multi_arr = np.arange(20).reshape(<<your code comes here>>)

(3) Extract values from row index numbers 2 to 4 and from column index numbers 2 to 5, and store it in a variable called my_multi_arr_portion

my_multi_arr_portion = my_multi_arr[<<your code comes here>>]

(4) Print the my_multi_arr_portion array using print() function to see its values

print(<<your code comes here>>)

No hints are availble for this assesment

Answer is not availble for this assesment


Note - Having trouble with the assessment engine? Follow the steps listed here

Loading comments...