0

I'm having a weird problem that I can't fix. I've created a Numpy array named arr:

import numpy as np

v1 = 1
e1 = [1, 2]
arr1 = [v1, e1] # Numpy array's first element

v2 = 2
e2 = [3, 5]
arr2 = [v2, e2] # Numpy array's second element

arr = np.array([arr1, arr2]) # My Numpy array
# array([[1, list([1, 2])],
#        [2, list([3, 5])]], dtype=object)

I want to find the position(s) of the list [3, 5] in the array arr (of course, by taking into account the placement of the list object in the latter [2nd column of each line]). So, I tried this command:

arr[:, 1] == [3, 5]
# array([False, False])

However, I am supposed to get: array([False, True]) (The list [3, 5] exists in the second line of arr).

To verify, I've tried to test the equality manually. Everything is ok, I've got expected results:

arr[:, 1][0] == [3, 5] # False
arr[:, 1][1] == [3, 5] # True

So, why by using the equality between arr and [3, 5] I've got array([False, False]) instead of array([False, True])?

Soufian
  • 61
  • 6
  • The duplicate is rather dated (2013), but in general working with object dtype arrays is not as straight forward as working with numeric ones. In one way or other `numpy` has to 'fudge', iterating on the elements, delegating the comparison to the elements, etc. Other than being able index with `arr[:,i]`, this array has few, if any, advantages relative to the list `[arr1, arr2]`. – hpaulj Apr 30 '20 at 18:54
  • I think `arr[:,1]==[3,5]` is actually doing `arr[:,1]==np.array([3,5])`, with all the array broadcasting rules. To do the test you want you have to construct or extract a 1 element object array containing the list `[3,5]`, e.g. `arr[:,1] == np.array(arr2)[[1]] ` – hpaulj Apr 30 '20 at 19:17
  • @yatu, I don't think this is a `contains` issue. It's more how `numpy` does an `==` test between two arrays. It isn't doing a simple list equality test. – hpaulj Apr 30 '20 at 19:40
  • True, reopened @hpaulj . Indeed it seems that each element in the list gets broadcasted across `arr`. Testing with `arr==(1,[1,2])` produces True for both elements in the first row, whereas `arr==[1,2]` only for the first element – yatu Apr 30 '20 at 19:57

1 Answers1

1

I think arr[:,1]==[3,5] is actually doing arr[:,1]==np.array([3,5]), with all the array broadcasting rules.

To do the test you want you have to construct or extract a 1 element object array containing the list [3,5], e.g.

arr[:,1] == np.array(arr2)[[1]] 
hpaulj
  • 221,503
  • 14
  • 230
  • 353