[Numpy-discussion] str == int puzzlement

Sturla Molden sturla@molden...
Wed Jul 28 21:24:14 CDT 2010


>
>> I'll call this a bug in NumPy's broadcasting. "x == 1" should have
>> returned:
>
> This is probably related:
>
>
> In [22]: a = np.array(['a','b'])
>
> In [23]: a + 'c'
> ---------------------------------------------------------------------------
> TypeError                                 Traceback (most recent call
> last)
>
> C:\Windows\system32\<string> in <module>()
>
> TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'str'
>
> In [24]: a + 1
> ---------------------------------------------------------------------------
> TypeError                                 Traceback (most recent call
> last)
>
> C:\Windows\system32\<string> in <module>()
>
> TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'int'


And setting the dtype to object, we get the correct behavior:

In [30]: a = np.array(['a','b'],dtype=object)

In [31]: a == 1
Out[31]: array([False, False], dtype=bool)

In [32]: a + 'c'
Out[32]: array([ac, bc], dtype=object)

In [33]: a + 1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

C:\Windows\system32\<string> in <module>()

TypeError: cannot concatenate 'str' and 'int' objects




The bug also seems to affect arrays with unicode strings, btw.


Sturla








More information about the NumPy-Discussion mailing list