Issue
I have an numpy array as the following
all = [[0 0 0],[0 0 1],[0 0 2], ... , [0 0 12]]
I am trying to only show the array which has third value 12. In this case [0 0 12]. When I execute my code I get the following output
[[0 0 0],[0 0 0],[0 0 12]]
I do not know why I get those 0 arrays. My code is below.
for i in all:
if i[2]==12:
print(all[i]) ```
Solution
You can use boolean mask:
When you print your array, you get:
print(arr)
array([[ 0, 0, 0],
[ 0, 0, 1],
[ 0, 0, 2],
[ 0, 0, 12]])
The third row is:
array([[ 0],
[ 1],
[ 2],
[12]])
Now, you can create a boolean mask as:
arr[:,2]==12
which evaluates to
array([False, False, False, True])
this means rows 1-3 don't have 12 as a third element but 4th does.
So you use this mask on arr
:
arr[arr[:,2]==12]
Output:
array([[ 0, 0, 12]])
Answered By - enke
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.