1

I have a NumPy array such as this:

[ 1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1
  1  1  1  1  1  1  1  1  1  1  1 -1  1  1  1  1  1  1  1  1  1  1  1  1
  1  1  1  1  1  1  1  1  1  1  1 -1  1  1  1  1  1  1  1  1  1  1  1  1
  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1
  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1 -1 -1 -1
  1  1  1  1  1  1 -1  1 -1  1  1  1  1  1  1  1  1  1  1  1  1 -1  1 -1
 -1 -1 -1  1  1 -1 -1 -1 -1 -1  1 -1 -1  1  1  1  1  1 -1  1  1  1  1  1
  1  1  1  1  1  1  1 -1 -1  1  1  1  1  1  1  1 -1  1  1  1  1  1  1  1
 -1  1  1  1  1  1  1  1  1 -1 -1 -1 -1 -1  1  1  1  1  1  1  1  1 -1  1
  1 -1 -1  1  1  1  1  1  1]

I am trying to access the index of an elements equaling -1 in a np array. I found NumPy has an equivalent to list.index but I keep getting an attribute error: 'numpy.ndarray' object has no attribute 'where'

I saw here Is there a NumPy function to return the first index of something in an array? that I should use where, however when I try the following I get the above error:

for pred in outlier_preds:
    if pred == -1:
        index = where(predictions)

I also tried:

for pred in outlier_preds:
    if pred == -1:
        index = outlier_preds.where(pred == -1)
        outlier_indecies.append(index)

And:

for pred in outlier_preds:
    if pred == -1:
        index = outlier_preds.where(preds)

There is obviously an attribute where() but for some reason it isn't working, I guess the way I am trying to use it?

Obviously I can get around it by converting it to a list but I would like to know how to use where correctly if possible

CDJB
  • 14,043
  • 5
  • 29
  • 55
codiearcher
  • 373
  • 1
  • 3
  • 12

1 Answers1

4

From the docs of numpy.where - the function returns the indexes where the condition within the function is True.

Example:

>>> np.where(outlier_preds == -1)
(array([ 35,  59, 117, 118, 119, 126, 128, 141, 143, 144, 145, 146, 149,
        150, 151, 152, 153, 155, 156, 162, 175, 176, 184, 192, 201, 202,
        203, 204, 205, 214, 217, 218], dtype=int64),)
>>> np.where(outlier_preds == -1)[0][0] #First element only
35
CDJB
  • 14,043
  • 5
  • 29
  • 55