0

I just learn about numpy and array today and I am quite confused about something. I don’t get line 3 as I thought np.array() should have a list in the (). Can someone explain that line to me? And for line 5, I know it is comparing array x and y. But can someone explain to me how it works? And what does x[y] mean? Thank you so much.

import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.array(x<4)
print(y)
print(x[y])

2 Answers 2

1

What this code snippet does is masking the x array with a condition. x[y] is the masked array, which shows only the elements of x where y is True (in that case where x < 4).

y = np.array(x < 4) has an useless np.array call, as x < 4 is already a numpy array. That being said, you can give many objects to np.array() such as lists, tuples, other arrays...

The whole thing should be simply:

import numpy as np
x = np.array([1, 2, 3, 4, 5])
print(x[x < 4])
# [1 2 3]
0

Line three tells you the places in x where the value is less than four. You don't need the "np.array" constructor out front though - y = x<4 will return you the same array.

Line five filters the x array, using the values in y that are 'True'. This is often referred to as a 'mask'.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.