Skip to content

Calling searchsorted on an int haystack with str needle converts haystack to str #6061

Open

Description

@levitsky

With numpy 1.9.2 I see quite counter-intuitive behavior of searchsorted on integer arrays with a str needle:

In [1]: import numpy as np

In [2]: a = np.arange(1000, dtype=int)

In [3]: a.searchsorted('15')
Out[3]: 150

In [4]: a.searchsorted('150')
Out[4]: 150

In [5]: a.searchsorted('1500')
Out[5]: 151

In [6]: a.searchsorted('foo')
Out[6]: 1000

The main reason why I believe this behavior is broken is because when one converts an integer array to strings, it's not sorted anymore.
I believe that the least surprising result would be an exception, especially because this is what happens if the array contains floats and not integers.

P.S. I initially asked about this on StackOverflow, and @jaimefrio suggested creating a bug report in the comments.

Activity

  1. jaimefrio commented on Jul 10, 2015

    @jaimefrio
    Member

    I think fixing this boils down to whether it is a searchsorted bug, and we need to put a special check there, or it really is a can_cast bug, and we should disallow safe casting of ints to strings, as we already do for floats.

  2. njsmith commented on Jul 10, 2015

    @njsmith
    Member

    +1 to making int->str considered not-safe. Generally "safe" for us means
    "should be implicitly coerceable", and python in general does not allow
    implicit coercion of int->str, so this seems pretty correct to me.
    On Jul 10, 2015 12:33 PM, "Jaime" [email protected] wrote:

    I think fixing this boils down to whether it is a searchsorted bug, and
    we need to put a special check there, or it really is a can_cast bug, and
    we should disallow safe casting of ints to strings, as we already do for
    floats.

    —
    Reply to this email directly or view it on GitHub
    #6061 (comment).

  3. OmerJog commented on May 23, 2019

    @OmerJog

    Is there a fix for this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions