Home > Blockchain >  Choosing a column which has a certain value
Choosing a column which has a certain value

Time:12-14

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]) ```

CodePudding user response:

You can select all the value of your arrays that correspond to your condition.

import numpy as np

arr = np.array([[0, 0, 0],
                [0, 0, 1],
                [0, 0, 2],
                [0, 0, 10],
                [0, 0, 11],
                [0, 0, 12]])

print(arr[arr[:,2]==12])

Output

[[ 0  0 12]]

CodePudding user response:

Try this (I am sure that there is a most efficient way to do it rather than a for loop, take a look to the docs of numpy or here in stackoverflow):

import numpy as np
# turn list of lists into a numpy array
all = np.array([[0,0,0],[0,0,0],[0,0,12]])

# use enumerate if you want so you can have the index
for i,ar in enumerate(all.tolist()):
  # look for your value
  if ar[2]==12:
      # as you want the rows just do all[i]
      # if you want the column also all[i][3]
      print( all[i] )

CodePudding user response:

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]])
  • Related