tags:

views:

47

answers:

2

The numpy.equal function does not work if a list or array contains strings:

>>> import numpy
>>> index = numpy.equal([1,2,'a'],None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: function not supported for these types, and can't coerce safely to supported types

What is the easiest way to workaround this without looping through each element? In the end, I need index to contain a boolean array indicating which elements are None.

+1  A: 

What's wrong with a stock list comprehension?

index = [x is None for x in L]
Ignacio Vazquez-Abrams
+2  A: 

If you really need to use numpy, be more careful about what you pass in and it can work:

>>> import numpy
>>> a = numpy.array([1, 2, 'a'], dtype=object) # makes type of array what you need
>>> numpy.equal(a, None)
array([False, False, False], dtype=bool)

Since you start with a list, there's a chance what you really want is just a list comprehension like [item is None for item in [1, 2, 'a']] or the similar generator expression.

To have an a heterogeneous list like this is odd. Lists (and numpy arrays) are typically used for homogeneous data.

Mike Graham