igorcantele / Internship

0 stars 0 forks source link

Inefficient indexing #7

Closed Helveg closed 3 years ago

Helveg commented 3 years ago

https://github.com/Igor10798/Internship/blob/9c8a19fcba446cb2e43bf0a8b77ce410f15c4c85/first_network/script.py#L52-L56

Some tips and tricks for numpy:

a = np.array([10, 20, 30, 40, 50])
ind = np.nonzero(a > 25)[0]
b = a[ind]

creates one more intermediate array and does more lookups so it is slower and less memory efficient compared to "boolean masking":

a = np.array([10, 20, 30, 40, 50])
mask = a > 25
b = a[mask]

Your first approach generates the boolean mask, but then has np.nonzero transform it into an array of indexes, which is not necessary as the boolean mask itself can immediately be used to index the array :)

a = np.array([10, 20, 30, 40, 50])
b = a[a > 25]