Reputation: 41
import numpy as np
x1 = np.array([[1,2,3],[4,5,6],[7,8,9]])
x1[ x1[:,1]>3 ]
For the code shown in upon, I don't understand why the output is
array([[4, 5, 6],[7, 8, 9]])
.
Upvotes: 4
Views: 90
Reputation: 1984
Break it down:
In [10]: x1
Out[10]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
In [11]: x1[:,1] # select all rows, second column
Out[11]: array([2, 5, 8])
In [12]: x1[:,1]>3 # for each one of these, return whether it's > 3
Out[12]: array([False, True, True])
In [13]: x1[ x1[:,1]>3 ] # This is "Boolean array indexing"
Out[13]:
array([[4, 5, 6],
[7, 8, 9]])
The "Boolean array indexing" part filters the rows of x1
depending on the booleans contained in the boolean array x1[:,1]>3
.
See Boolean array indexing in numpy doc.
Upvotes: 2
Reputation: 608
It will retrieve all rows whose value is greater than 3. : is used to slice row and columns from array
Upvotes: 2