2

I want to have a boolean numpy array fixidx that is the result of comparing numpy arrays a, b, c and d. For example I have the arrays

a = np.array([1, 1])
b = np.array([1, 2])
c = np.array([1, 3])
d = np.array([1, 4])

so the array fixidx has the values

fixidx = [1, 0]

My approach was

fixidx = (a == b) & (b == c) & (c == d)

This works in Matlab but as it turns out Python only puts out a ValueError.

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

any or all won't do the trick or at least I couldn't figure it out.

1
  • 1
    Code works perfectly with no errors. Try ((a == b) & (b == c) & (c == d)).astype(int) to get [1,0]. Commented Aug 31, 2018 at 11:42

2 Answers 2

1

Code works perfectly with no errors. Try converting boolean output to integer:

((a == b) & (b == c) & (c == d)).astype(int)
array([1, 0])
Sign up to request clarification or add additional context in comments.

1 Comment

You're right, it works perfectly fine. Strange. I can't explain why I got this error message.
1

Let's start by stacking a, b, c and d into a single array x:

In [452]: x = np.stack([a, b, c, d])

In [453]: x
Out[453]: 
array([[1, 1],
       [1, 2],
       [1, 3],
       [1, 4]])

Then you can apply NumPy's unique to each column and test whether the result has one or more elements.

In [454]: fixidx = np.array([np.unique(x[:, i]).size == 1 for i in range(x.shape[1])])

In [455]: fixidx
Out[455]: array([ True, False])

Finally you can cast fixidx to integer if necessary:

In [456]: fixidx.astype(int)
Out[456]: array([1, 0])

Alternatively, you could obtain the same result through NumPy's equal as follows:

fixidx = np.ones(shape=a.shape, dtype=int)
x = [a, b, c, d]
for first, second in zip(x[:-1], x[1:]):
    fixidx *= np.equal(first, second)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.