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!

2
  • Check this: stackoverflow.com/questions/36960830/… Commented Jul 18, 2017 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. Commented Jul 18, 2017 at 17:18

1 Answer 1

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))
Sign up to request clarification or add additional context in comments.

2 Comments

Hmm, that makes sense. Do you know how I would convert vectors into that format?
I edited the answer for the correct conversion, let me know if this solution works for you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.