开发者

numpy.equal with string values

开发者 https://www.devze.com 2022-12-23 09:01 出处:网络
The numpy.equal function does not work if a list or array contains strings: >>> import numpy >>> index = numpy.equal([1,2,\'a\'],None)

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 w开发者_如何学Cay to workaround this without looping through each element? In the end, I need index to contain a boolean array indicating which elements are None.


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.


What's wrong with a stock list comprehension?

index = [x is None for x in L]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号