-1
In [7]: a
Out[7]: array(['107', '207', '307', '407'], dtype=object)

In [8]: v
Out[8]: array([207, 305, 407, 101])

In [9]: np.searchsorted(a, v)
Out[9]: array([0, 0, 0, 0])

With Python 3 however, I get

In [20]: a
Out[20]: array(['107', '207', '307', '407'], dtype=object)

In [21]: v
Out[21]: array([207, 305, 407, 101])

In [22]: np.searchsorted(a, v)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-22-52fb08e43089> in <module>()
----> 1 np.searchsorted(a, v)

/tmp/py3test/lib/python3.4/site-packages/numpy/core/fromnumeric.py in searchsorted(a, v, side, sorter)
   1091     except AttributeError:
   1092         return _wrapit(a, 'searchsorted', v, side, sorter)
-> 1093     return searchsorted(v, side, sorter)
   1094 
   1095 

TypeError: unorderable types: str() > int()

My question would be: Is this expected behaviour on Python3 or a bug? And in any case: How can I make my Python 2 code compatible with both Python versions?

wirrbel
  • 3,173
  • 3
  • 26
  • 49

1 Answers1

2

Search with strings,

In [278]: a=np.array(['107', '207', '307', '407'], dtype=object)
In [279]: a
Out[279]: array(['107', '207', '307', '407'], dtype=object)
In [280]: np.searchsorted(a,'207')
Out[280]: 1
In [281]: np.searchsorted(a,207)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-281-a2d90678474c> in <module>()
----> 1 np.searchsorted(a,207)

/usr/local/lib/python3.5/dist-packages/numpy/core/fromnumeric.py in searchsorted(a, v, side, sorter)
   1091     except AttributeError:
   1092         return _wrapit(a, 'searchsorted', v, side, sorter)
-> 1093     return searchsorted(v, side, sorter)
   1094 
   1095 

TypeError: unorderable types: str() > int()

or numbers:

In [282]: np.searchsorted(a.astype(int),207)
Out[282]: 1

Don't try to mix strings and numbers without understanding how they interact.

If Py2 gave 0 instead of an error, it is just because it is being careless about the comparison of numbers and strings.

In Py3:

In [283]: '207'>207
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-283-834e0a472e1a> in <module>()
----> 1 '207'>207

TypeError: unorderable types: str() > int()

In py2.7

>>> '207'>207
True
hpaulj
  • 221,503
  • 14
  • 230
  • 353