Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

.loc interprets slice as positional rather than label-based when setting #16121

Closed
toobaz opened this issue Apr 24, 2017 · 1 comment · Fixed by #31840
Closed

.loc interprets slice as positional rather than label-based when setting #16121

toobaz opened this issue Apr 24, 2017 · 1 comment · Fixed by #31840
Labels
Bug Indexing Related to indexing on series/frames, not to indexes themselves
Milestone

Comments

@toobaz
Copy link
Member

toobaz commented Apr 24, 2017

Code Sample, a copy-pastable example if possible

In [2]: df = pd.DataFrame(-1, index=['i', 'ii', 'iii'], columns=pd.MultiIndex.from_tuples([['A', 'a'], ['B', 'b']]))

In [3]: df.loc[1:, 'A'] = ''

In [4]: df
Out[4]: 
      A  B
      a  b
i    -1 -1
ii      -1
iii     -1

In [5]: df.loc[1:, 'A']
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-98b6153a5b09> in <module>()
----> 1 df.loc[1:, 'A']

/home/pietro/nobackup/repo/pandas/pandas/core/indexing.py in __getitem__(self, key)
   1322             except (KeyError, IndexError):
    948 
    949         # we maybe be using a tuple to represent multiple dimensions here

/home/pietro/nobackup/repo/pandas/pandas/core/indexing.py in _getitem_nested_tuple(self, tup)
   1020 
   1021             current_ndim = obj.ndim
-> 1022             obj = getattr(obj, self.name)._getitem_axis(key, axis=axis)
   1023             axis += 1
   1024 

/home/pietro/nobackup/repo/pandas/pandas/core/indexing.py in _getitem_axis(self, key, axis)
   1503         if isinstance(key, slice):
   1504             self._has_valid_type(key, axis)
-> 1505             return self._get_slice_axis(key, axis=axis)
   1506         elif is_bool_indexer(key):
   1507             return self._getbool_axis(key, axis=axis)

/home/pietro/nobackup/repo/pandas/pandas/core/indexing.py in _get_slice_axis(self, slice_obj, axis)
   1353         labels = obj._get_axis(axis)
   1354         indexer = labels.slice_indexer(slice_obj.start, slice_obj.stop,
-> 1355                                        slice_obj.step, kind=self.name)
   1356 
   1357         if isinstance(indexer, slice):

/home/pietro/nobackup/repo/pandas/pandas/indexes/base.py in slice_indexer(self, start, end, step, kind)
   3247         """
   3248         start_slice, end_slice = self.slice_locs(start, end, step=step,
-> 3249                                                  kind=kind)
   3250 
   3251         # return a slice

/home/pietro/nobackup/repo/pandas/pandas/indexes/base.py in slice_locs(self, start, end, step, kind)
   3428         start_slice = None
   3429         if start is not None:
-> 3430             start_slice = self.get_slice_bound(start, 'left', kind)
   3431         if start_slice is None:
   3432             start_slice = 0

/home/pietro/nobackup/repo/pandas/pandas/indexes/base.py in get_slice_bound(self, label, side, kind)
   3367         # For datetime indices label may be a string that has to be converted
   3368         # to datetime boundary according to its resolution.
-> 3369         label = self._maybe_cast_slice_bound(label, side, kind)
   3370 
   3371         # we need to look up the label

/home/pietro/nobackup/repo/pandas/pandas/indexes/base.py in _maybe_cast_slice_bound(self, label, side, kind)
   3325         # this is rejected (generally .loc gets you here)
   3326         elif is_integer(label):
-> 3327             self._invalid_indexer('slice', label)
   3328 
   3329         return label

/home/pietro/nobackup/repo/pandas/pandas/indexes/base.py in _invalid_indexer(self, form, key)
   1447                         "indexers [{key}] of {kind}".format(
   1448                             form=form, klass=type(self), key=key,
-> 1449                             kind=type(key)))
   1450 
   1451     def get_duplicates(self):

TypeError: cannot do slice indexing on <class 'pandas.indexes.base.Index'> with these indexers [1] of <class 'int'>

Problem description

In[3]: should already raise an error (unless the label 1 is compared against the labels in the index, in which case it should certainly be smaller or larger than each of them).

Expected Output

An error

Output of pd.show_versions()

INSTALLED VERSIONS

commit: None
python: 3.5.3.final.0
python-bits: 64
OS: Linux
OS-release: 3.16.0-4-amd64
machine: x86_64
processor:
byteorder: little
LC_ALL: None
LANG: en_GB.UTF-8
LOCALE: en_GB.UTF-8

pandas: 0.19.0+783.gcd35d22a0
pytest: 3.0.6
pip: 1.5.6
setuptools: 5.5.1
Cython: 0.25.2
numpy: 1.12.1
scipy: 0.18.1
xarray: None
IPython: 5.2.2
sphinx: None
patsy: 0.4.1+dev
dateutil: 2.6.0
pytz: 2016.10
blosc: None
bottleneck: None
tables: 3.3.0
numexpr: 2.6.1
feather: 0.3.1
matplotlib: 2.0.0
openpyxl: 2.3.0
xlrd: 0.9.2
xlwt: 1.2.0
xlsxwriter: None
lxml: 3.7.1
bs4: None
html5lib: 0.999
sqlalchemy: 0.9.8
pymysql: None
psycopg2: None
jinja2: 2.7.3
s3fs: None
pandas_gbq: None
pandas_datareader: None

@jorisvandenbossche
Copy link
Member

Note that in this case the MultiIndex is not needed to reproduce the issue (which you didn't say, but just to not complicate the example):

In [27]: df = pd.DataFrame(-1, index=['i', 'ii', 'iii'], columns=['A', 'B'])

In [28]: df.loc[1:, 'A']
...
TypeError: cannot do slice indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [1] of <class 'int'>

In [29]: df.loc[1:, 'A'] = 1

In [30]: df
Out[30]: 
     A  B
i   -1 -1
ii   1 -1
iii  1 -1

@jorisvandenbossche jorisvandenbossche added Bug Indexing Related to indexing on series/frames, not to indexes themselves labels Apr 25, 2017
@jreback jreback added this to the 1.1 milestone Feb 22, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Indexing Related to indexing on series/frames, not to indexes themselves
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants