4

With the following arrays of objects:

a = np.array([[1], [1, 2], [1, 2, 3], [1], [1]], dtype=object)
b = np.array([(1,), (1, 2), (1, 2, 3), (1,), (1,)], dtype=object)

The following equality checks do not work:

a==[1]
#array([False, False, False, False, False], dtype=bool)

b==(1,)
#array([False, False, False, False, False], dtype=bool)

if I use strings instead:

c = np.array(['[1]', '[1, 2]', '[1, 2, 3]', '[1]', '[1]'])

the equality check works:

c == '[1]'
#array([ True, False, False,  True,  True], dtype=bool)

why the array check behaves like that?

If we iterate over a or b and perform the checks it also gives the expected result:

[i==[1] for i in a]
#[True, False, False, True, True]

[i==(1,) for i in b]
#[True, False, False, True, True]

Thank you!

1 Answer 1

6

NumPy is designed to automatically treat array-like objects as arrays in many situations. Here, NumPy sees that [1] and (1,) are array-like objects and applies the broadcasting rules. Length-1 axes on either side are expanded out to the length of the other object's corresponding axis, and if one object has less dimensions than the other, missing dimensions are filled in on the left with the other object's lengths in those dimensions. Thus,

a == [1]

gives the same result as

a == numpy.array([1, 1, 1, 1, 1])

which is an array of 5 Falses.

Sign up to request clarification or add additional context in comments.

4 Comments

thank you! Do you know a way to avoid the broadcasting rules such that a is compared to [1] element-wise?
Nope. My advice is to avoid using sequences (or arrays) as array elements. You might try wrapping them in some sort of definitely-not-a-list object, or see if masked arrays fit your use case.
You can make an empty shape-() array, then fill it with your [1] list. c=np.empty([], dtype=object); c[()] = [1]. That avoids the automatic attempt to interpret the list as its own array. Comparing a with c will give you the results you are after.
@RobertKern: Clever idea, but it makes the code a lot bigger, and if you don't do it everywhere, the places you forgot fail silently. I wouldn't recommend it.

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.