Skip to content

BUG: wrong/confusing error message in DataFrame.take with a scalar indexer #42875

Closed
@jorisvandenbossche

Description

@jorisvandenbossche
In [4]: df = pd.DataFrame({'a': [1, 2, 3]})

In [5]: df.take(1)
...

~/scipy/pandas/pandas/core/indexes/range.py in take(self, indices, axis, allow_fill, fill_value, **kwargs)
    433     ) -> Int64Index:
    434         with rewrite_exception("Int64Index", type(self).__name__):
--> 435             return self._int64index.take(
    436                 indices,
    437                 axis=axis,

~/scipy/pandas/pandas/core/indexes/base.py in take(self, indices, axis, allow_fill, fill_value, **kwargs)
    962             self._values, indices, allow_fill=allow_fill, fill_value=self._na_value
    963         )
--> 964         return type(self)._simple_new(taken, name=self.name)
    965 
    966     @final

~/scipy/pandas/pandas/core/indexes/base.py in _simple_new(cls, values, name)
    611         Must be careful not to recurse.
    612         """
--> 613         assert isinstance(values, np.ndarray), type(values)
    614 
    615         result = object.__new__(cls)

AssertionError: <class 'numpy.int64'>

take requires an array-like for the indexer, but when passing a scalar you get a not very useful error message as above. We should raise a ValueError (or rather TypeError) instead with an informative message.

It actually comes from the Index take implementation:

In [9]: pd.Index([1, 2, 3]).take(1)
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-9-ce9f87ba8bd2> in <module>
----> 1 pd.Index([1, 2, 3]).take(1)

~/scipy/pandas/pandas/core/indexes/base.py in take(self, indices, axis, allow_fill, fill_value, **kwargs)
    962             self._values, indices, allow_fill=allow_fill, fill_value=self._na_value
    963         )
--> 964         return type(self)._simple_new(taken, name=self.name)
    965 
    966     @final

~/scipy/pandas/pandas/core/indexes/base.py in _simple_new(cls, values, name)
    611         Must be careful not to recurse.
    612         """
--> 613         assert isinstance(values, np.ndarray), type(values)
    614 
    615         result = object.__new__(cls)

AssertionError: <class 'numpy.int64'>

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions