i have this two numpy arrays
arr1 = np.empty( (3,) , dtype=np.object)
arr1[0] = [1,2]
arr1[1] = [1,2,3]
arr1[2] = None
arr2 = np.empty( (3,) , dtype=np.object)
arr2[0] = np.array([1,2])
arr2[1] = np.array([1,2,3])
arr2[2] = None
why , when i'm checking if the internal array/list is None i'm getting different results both have the same shape
In [28]: arr1 != None
Out[28]: array([ True, True, False])
In [27]: arr2 != None
Out[27]: True
what is the way in numpy to check, that each element in arr2 is None?
CodePudding user response:
Note that the line arr2 != None
raises the following DeprecationWarning on newer versions of Numpy:
Warning (from warnings module):
File "<pyshell#19>", line 1
DeprecationWarning: elementwise comparison failed; this will raise an error in the future.
The reason is that my_array != my_object
calls my_array[i] != my_object
for each i
, and expects to get back a boolean value at each element. Instead though, it gets back array([ False, False])
as the first element (not just a boolean).
So essentially, the difference is that list != None
returns False, but numpy_array_of_ints != None
returns an array. Elementwise comparisons should only return an array of booleans.
Edit: looking at the docs, the return value of elementwise comparisons are "Typically of type bool, unless dtype=object is passed." As such, we can do this:
>>> np.not_equal(arr1, None, dtype=object)
array([True, True, False], dtype=object)
>>> np.not_equal(arr2, None, dtype=object)
array([array([ True, True]), array([ True, True, True]), False],
dtype=object)