0

I have a list of 50 numpy arrays called vectors:

[array([0.1, 0.8, 0.03, 1.5], dtype=float32), array([1.2, 0.3, 0.1], dtype=float32), .......]

I also have a smaller list (means) of 10 numpy arrays, all of which are from the bigger list above. I want to loop though each array in means and find its position in vectors.

So when I do this:

for c in means:
        print(vectors.index(c))

I get the error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I've gone through various SO questions and I know why I'm getting this error, but I can't find a solution. Any help?

Thanks!

dvn
  • 41
  • 1
  • 9
  • Check this: https://stackoverflow.com/questions/36960830/python-list-of-numpy-arrays-cant-do-index – Rakesh Adhikesavan Jul 18 '17 at 16:46
  • 1
    `vectors` is a list; `vectors.index` does `v==c` for all elements until this test is `True`. But with array elements `v==c` returns a boolean array, a `True/False` value for each element of `v`. That's the meaning of the ValueError - many boolean values in a context that expects just one. – hpaulj Jul 18 '17 at 17:18

1 Answers1

1

One possible solution is converting to a list.

vectors = np.array([[1, 2, 3], [4, 5, 6], [7,8,9], [10,11,12]], np.int32)

print vectors.tolist().index([1,2,3])

This will return index 0, because [1,2,3] can be found in index 0 of vectors

Th example above is a 2d Numpy array, however you seem to have a list of numpy arrays,

so I would convert it to a list of lists this way:

vectors = [arr.tolist() for arr in vectors]

Do the same for means:

means = [arr.tolist() for arr in means]

Now we are working with two lists of lists:

So your original 'for loop' will work:

for c in means:
    print(vectors.index(c))
Rakesh Adhikesavan
  • 11,966
  • 18
  • 51
  • 76