...

/

Smart Array Programming

Smart Array Programming

In this lesson, we will discuss some smart programming tools for arrays.

Using conditions on arrays #

You can perform comparison statements on arrays, and it will return an array of booleans (True and False values) for each value in the array. For example, let’s create an array and find out which values of the array are below 5:

Press + to interact
import numpy as np
a = np.arange(10)
print('the total array:', a)
print("array of booleans:", a < 5)
print('values less than 5:', a[a < 5])

If we want to replace every value that is less than 5 with 666, we can use the following short syntax:

Press + to interact
import numpy as np
a = np.arange(10)
print(a)
a[a < 5] = 666
print(a)

Using multiple conditions #

Multiple conditions can be given as well. When two conditions both have to be true, use the & symbol. When at least one of the conditions needs to be true, use the | symbol (that is the vertical bar).

Let’s use the & symbol:

Press + to interact
import numpy as np
a = np.arange(20)
print(a)
a[(a > 5) & (a < 10)] = 666
print(a)

Since only the values 6,7,86, 7, 8 ...