Skip to content

BUG: strange behavior of .loc indexer: falling back to integer-based indexing with list  #7496

Closed
@code-of-kpp

Description

@code-of-kpp
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas
>>> a = pandas.Series()
>>> a.loc[1] = 1
>>> a.loc['a'] = 2
>>> a.loc[[-1, -2]]
1    1
a    2
dtype: int64

This is ok:

>>> a.loc[-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/tmp/venv/local/lib/python2.7/site-packages/pandas/core/indexing.py", line 1129, in __getitem__
    return self._getitem_axis(key, axis=0)
  File "/tmp/venv/local/lib/python2.7/site-packages/pandas/core/indexing.py", line 1261, in _getitem_axis
    self._has_valid_type(key, axis)
  File "/tmp/venv/local/lib/python2.7/site-packages/pandas/core/indexing.py", line 1234, in _has_valid_type
    error()
  File "/tmp/venv/local/lib/python2.7/site-packages/pandas/core/indexing.py", line 1221, in error
    (key, self.obj._get_axis_name(axis)))
KeyError: 'the label [-1] is not in the [index]'

This is ok too:

>>> a.loc[['W']]
W   NaN
dtype: float64

But this is not:

>>> a.loc[-1] = 3
>>> a.loc[[-1, -2]]
-1    3
1    1
dtype: int64

And this is not good at all:

>>> a
1    1
-1    3
dtype: int64
>>> a['a'] = 2
>>> a
1     1
-1    3
a     2
dtype: int64
>>> a.loc[[-2]] = 0
>>> a
1     0
-1    3
a     2
dtype: int64

Without 'a' string in the index it raises while I expect new item ({-2: 0}) to be added

>>> del a['a']
>>> a.loc[[-2]] = 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/tmp/venv/local/lib/python2.7/site-packages/pandas/core/indexing.py", line 117, in __setitem__
    indexer = self._convert_to_indexer(key, is_setter=True)
  File "/tmp/venv/local/lib/python2.7/site-packages/pandas/core/indexing.py", line 1068, in _convert_to_indexer
    raise KeyError('%s not in index' % objarr[mask])
KeyError: '[-2] not in index'

Metadata

Metadata

Assignees

No one assigned

    Labels

    API DesignBugIndexingRelated to indexing on series/frames, not to indexes themselves

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions