Profile picture

1.4 - Boolean Arrays

Last updated: February 21st, 20192019-02-21Project preview

rmotr


Filtering with Boolean Arrays - Exercises

In [ ]:
import numpy as np

green-divider

Exercise 1

Using NumPy, create the following matrix:

  • $ A = \begin{bmatrix} -8 & -4 & 10 \\ 2 & -12 & 1 \\ -5 & 7 & -9 \\ 11 & -3 & 6 \\ \end{bmatrix} $
In [ ]:
# your code goes here
In [ ]:
A = np.array([[-8, -4, 10],
              [2, -12, 1],
              [-5, 7, -9],
              [11, -3, 6]])

green-divider

Exercise 2

Get all the positive elements in A.

In [ ]:
# your code goes here
In [ ]:
A[A > 0]

green-divider

Exercise 3

Get all the elements that are positive and less than 8 in A.

In [ ]:
# your code goes here
In [ ]:
A[(A > 0) & (A < 8)]

green-divider

Exercise 4

Get all the negative or greater than 10 elements in A.

In [ ]:
# your code goes here
In [ ]:
A[(A < 0) | (A > 10)]

green-divider

Exercise 5

Add 20 to all negative elements in A matrix.

In [ ]:
# your code goes here
In [ ]:
A[A < 0] += 20
A

green-divider

Exercise 6

Check if there is any element greater than or equals to 15 in A matrix.

In [ ]:
# your code goes here

You can try using any() Numpy method on the matrix.

In [ ]:
(A >= 15).any()

green-divider

Exercise 7

Check if all the elements in A matrix are even.

In [ ]:
# your code goes here

You can try using all() Numpy method on the matrix.

In [ ]:
(A % 2 == 0).all()

green-divider

Exercise 8

Get the sum of all the even numbers in A matrix.

In [ ]:
# your code goes here
In [ ]:
np.sum(A[A % 2 == 0])

purple-divider

Notebooks AI
Notebooks AI Profile20060