Skip to content

Commit 8e89cb3

Browse files
authored
API: warning to raise KeyError in the future if not all elements of a list are selected via .loc (pandas-dev#17295)
closes pandas-dev#15747
1 parent 170411f commit 8e89cb3

17 files changed

+386
-67
lines changed

doc/source/advanced.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -1009,7 +1009,7 @@ The different indexing operation can potentially change the dtype of a ``Series`
10091009
10101010
series1 = pd.Series([1, 2, 3])
10111011
series1.dtype
1012-
res = series1[[0,4]]
1012+
res = series1.reindex([0, 4])
10131013
res.dtype
10141014
res
10151015

doc/source/indexing.rst

+110-2
Original file line numberDiff line numberDiff line change
@@ -333,8 +333,15 @@ Selection By Label
333333
334334
dfl.loc['20130102':'20130104']
335335
336+
.. warning::
337+
338+
Starting in 0.21.0, pandas will show a ``FutureWarning`` if indexing with a list with missing labels. In the future
339+
this will raise a ``KeyError``. See :ref:`list-like Using loc with missing keys in a list is Deprecated <indexing.deprecate_loc_reindex_listlike>`
340+
336341
pandas provides a suite of methods in order to have **purely label based indexing**. This is a strict inclusion based protocol.
337-
**At least 1** of the labels for which you ask, must be in the index or a ``KeyError`` will be raised! When slicing, both the start bound **AND** the stop bound are *included*, if present in the index. Integers are valid labels, but they refer to the label **and not the position**.
342+
All of the labels for which you ask, must be in the index or a ``KeyError`` will be raised!
343+
When slicing, both the start bound **AND** the stop bound are *included*, if present in the index.
344+
Integers are valid labels, but they refer to the label **and not the position**.
338345

339346
The ``.loc`` attribute is the primary access method. The following are valid inputs:
340347

@@ -635,6 +642,107 @@ For getting *multiple* indexers, using ``.get_indexer``
635642
dfd.iloc[[0, 2], dfd.columns.get_indexer(['A', 'B'])]
636643
637644
645+
.. _indexing.deprecate_loc_reindex_listlike:
646+
647+
Indexing with list with missing labels is Deprecated
648+
----------------------------------------------------
649+
650+
.. warning::
651+
652+
Starting in 0.21.0, using ``.loc`` or ``[]`` with a list with one or more missing labels, is deprecated, in favor of ``.reindex``.
653+
654+
In prior versions, using ``.loc[list-of-labels]`` would work as long as *at least 1* of the keys was found (otherwise it
655+
would raise a ``KeyError``). This behavior is deprecated and will show a warning message pointing to this section. The
656+
recommeded alternative is to use ``.reindex()``.
657+
658+
For example.
659+
660+
.. ipython:: python
661+
662+
s = pd.Series([1, 2, 3])
663+
s
664+
665+
Selection with all keys found is unchanged.
666+
667+
.. ipython:: python
668+
669+
s.loc[[1, 2]]
670+
671+
Previous Behavior
672+
673+
.. code-block:: ipython
674+
675+
In [4]: s.loc[[1, 2, 3]]
676+
Out[4]:
677+
1 2.0
678+
2 3.0
679+
3 NaN
680+
dtype: float64
681+
682+
683+
Current Behavior
684+
685+
.. code-block:: ipython
686+
687+
In [4]: s.loc[[1, 2, 3]]
688+
Passing list-likes to .loc with any non-matching elements will raise
689+
KeyError in the future, you can use .reindex() as an alternative.
690+
691+
See the documentation here:
692+
http://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reindex-listlike
693+
694+
Out[4]:
695+
1 2.0
696+
2 3.0
697+
3 NaN
698+
dtype: float64
699+
700+
701+
Reindexing
702+
~~~~~~~~~~
703+
704+
The idiomatic way to achieve selecting potentially not-found elmenents is via ``.reindex()``. See also the section on :ref:`reindexing <basics.reindexing>`.
705+
706+
.. ipython:: python
707+
708+
s.reindex([1, 2, 3])
709+
710+
Alternatively, if you want to select only *valid* keys, the following is idiomatic and efficient; it is guaranteed to preserve the dtype of the selection.
711+
712+
.. ipython:: python
713+
714+
labels = [1, 2, 3]
715+
s.loc[s.index.intersection(labels)]
716+
717+
Having a duplicated index will raise for a ``.reindex()``:
718+
719+
.. ipython:: python
720+
721+
s = pd.Series(np.arange(4), index=['a', 'a', 'b', 'c'])
722+
labels = ['c', 'd']
723+
724+
.. code-block:: ipython
725+
726+
In [17]: s.reindex(labels)
727+
ValueError: cannot reindex from a duplicate axis
728+
729+
Generally, you can interesect the desired labels with the current
730+
axis, and then reindex.
731+
732+
.. ipython:: python
733+
734+
s.loc[s.index.intersection(labels)].reindex(labels)
735+
736+
However, this would *still* raise if your resulting index is duplicated.
737+
738+
.. code-block:: ipython
739+
740+
In [41]: labels = ['a', 'd']
741+
742+
In [42]: s.loc[s.index.intersection(labels)].reindex(labels)
743+
ValueError: cannot reindex from a duplicate axis
744+
745+
638746
.. _indexing.basics.partial_setting:
639747

640748
Selecting Random Samples
@@ -852,7 +960,7 @@ when you don't know which of the sought labels are in fact present:
852960
s[s.index.isin([2, 4, 6])]
853961
854962
# compare it to the following
855-
s[[2, 4, 6]]
963+
s.reindex([2, 4, 6])
856964
857965
In addition to that, ``MultiIndex`` allows selecting a separate level to use
858966
in the membership check:

doc/source/whatsnew/v0.15.0.txt

+19-5
Original file line numberDiff line numberDiff line change
@@ -676,10 +676,19 @@ Other notable API changes:
676676

677677
Both will now return a frame reindex by [1,3]. E.g.
678678

679-
.. ipython:: python
679+
.. code-block:: ipython
680680

681-
df.loc[[1,3]]
682-
df.loc[[1,3],:]
681+
In [3]: df.loc[[1,3]]
682+
Out[3]:
683+
0
684+
1 a
685+
3 NaN
686+
687+
In [4]: df.loc[[1,3],:]
688+
Out[4]:
689+
0
690+
1 a
691+
3 NaN
683692

684693
This can also be seen in multi-axis indexing with a ``Panel``.
685694

@@ -693,9 +702,14 @@ Other notable API changes:
693702

694703
The following would raise ``KeyError`` prior to 0.15.0:
695704

696-
.. ipython:: python
705+
.. code-block:: ipython
697706

698-
p.loc[['ItemA','ItemD'],:,'D']
707+
In [5]:
708+
Out[5]:
709+
ItemA ItemD
710+
1 3 NaN
711+
2 7 NaN
712+
3 11 NaN
699713

700714
Furthermore, ``.loc`` will raise If no values are found in a multi-index with a list-like indexer:
701715

doc/source/whatsnew/v0.21.0.txt

+59
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,64 @@ If installed, we now require:
300300
| Bottleneck | 1.0.0 | |
301301
+--------------+-----------------+----------+
302302

303+
.. _whatsnew_0210.api_breaking.loc:
304+
305+
Indexing with a list with missing labels is Deprecated
306+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
307+
308+
Previously, selecting with a list of labels, where one or more labels were missing would always succeed, returning ``NaN`` for missing labels.
309+
This will now show a ``FutureWarning``, in the future this will raise a ``KeyError`` (:issue:`15747`).
310+
This warning will trigger on a ``DataFrame`` or a ``Series`` for using ``.loc[]`` or ``[[]]`` when passing a list-of-labels with at least 1 missing label.
311+
See the :ref:`deprecation docs <indexing.deprecate_loc_reindex_listlike>`.
312+
313+
314+
.. ipython:: python
315+
316+
s = pd.Series([1, 2, 3])
317+
s
318+
319+
Previous Behavior
320+
321+
.. code-block:: ipython
322+
323+
In [4]: s.loc[[1, 2, 3]]
324+
Out[4]:
325+
1 2.0
326+
2 3.0
327+
3 NaN
328+
dtype: float64
329+
330+
331+
Current Behavior
332+
333+
.. code-block:: ipython
334+
335+
In [4]: s.loc[[1, 2, 3]]
336+
Passing list-likes to .loc or [] with any missing label will raise
337+
KeyError in the future, you can use .reindex() as an alternative.
338+
339+
See the documentation here:
340+
http://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reindex-listlike
341+
342+
Out[4]:
343+
1 2.0
344+
2 3.0
345+
3 NaN
346+
dtype: float64
347+
348+
The idiomatic way to achieve selecting potentially not-found elmenents is via ``.reindex()``
349+
350+
.. ipython:: python
351+
352+
s.reindex([1, 2, 3])
353+
354+
Selection with all keys found is unchanged.
355+
356+
.. ipython:: python
357+
358+
s.loc[[1, 2]]
359+
360+
303361
.. _whatsnew_0210.api_breaking.pandas_eval:
304362

305363
Improved error handling during item assignment in pd.eval
@@ -607,6 +665,7 @@ Deprecations
607665
- ``pd.TimeGrouper`` is deprecated in favor of :class:`pandas.Grouper` (:issue:`16747`)
608666
- ``cdate_range`` has been deprecated in favor of :func:`bdate_range`, which has gained ``weekmask`` and ``holidays`` parameters for building custom frequency date ranges. See the :ref:`documentation <timeseries.custom-freq-ranges>` for more details (:issue:`17596`)
609667
- passing ``categories`` or ``ordered`` kwargs to :func:`Series.astype` is deprecated, in favor of passing a :ref:`CategoricalDtype <whatsnew_0210.enhancements.categorical_dtype>` (:issue:`17636`)
668+
- Passing a non-existant column in ``.to_excel(..., columns=)`` is deprecated and will raise a ``KeyError`` in the future (:issue:`17295`)
610669

611670
.. _whatsnew_0210.deprecations.argmin_min:
612671

pandas/core/indexing.py

+26-6
Original file line numberDiff line numberDiff line change
@@ -1419,13 +1419,33 @@ def _has_valid_type(self, key, axis):
14191419
if isinstance(key, tuple) and isinstance(ax, MultiIndex):
14201420
return True
14211421

1422-
# TODO: don't check the entire key unless necessary
1423-
if (not is_iterator(key) and len(key) and
1424-
np.all(ax.get_indexer_for(key) < 0)):
1422+
if not is_iterator(key) and len(key):
14251423

1426-
raise KeyError(u"None of [{key}] are in the [{axis}]"
1427-
.format(key=key,
1428-
axis=self.obj._get_axis_name(axis)))
1424+
# True indicates missing values
1425+
missing = ax.get_indexer_for(key) < 0
1426+
1427+
if np.any(missing):
1428+
if len(key) == 1 or np.all(missing):
1429+
raise KeyError(
1430+
u"None of [{key}] are in the [{axis}]".format(
1431+
key=key, axis=self.obj._get_axis_name(axis)))
1432+
else:
1433+
1434+
# we skip the warning on Categorical/Interval
1435+
# as this check is actually done (check for
1436+
# non-missing values), but a bit later in the
1437+
# code, so we want to avoid warning & then
1438+
# just raising
1439+
_missing_key_warning = textwrap.dedent("""
1440+
Passing list-likes to .loc or [] with any missing label will raise
1441+
KeyError in the future, you can use .reindex() as an alternative.
1442+
1443+
See the documentation here:
1444+
http://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reindex-listlike""") # noqa
1445+
1446+
if not (ax.is_categorical() or ax.is_interval()):
1447+
warnings.warn(_missing_key_warning,
1448+
FutureWarning, stacklevel=5)
14291449

14301450
return True
14311451

pandas/core/series.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -691,7 +691,7 @@ def _get_with(self, key):
691691

692692
if key_type == 'integer':
693693
if self.index.is_integer() or self.index.is_floating():
694-
return self.reindex(key)
694+
return self.loc[key]
695695
else:
696696
return self._get_values(key)
697697
elif key_type == 'boolean':

pandas/io/formats/excel.py

+15-1
Original file line numberDiff line numberDiff line change
@@ -356,7 +356,21 @@ def __init__(self, df, na_rep='', float_format=None, cols=None,
356356
self.styler = None
357357
self.df = df
358358
if cols is not None:
359-
self.df = df.loc[:, cols]
359+
360+
# all missing, raise
361+
if not len(Index(cols) & df.columns):
362+
raise KeyError(
363+
"passes columns are not ALL present dataframe")
364+
365+
# deprecatedin gh-17295
366+
# 1 missing is ok (for now)
367+
if len(Index(cols) & df.columns) != len(cols):
368+
warnings.warn(
369+
"Not all names specified in 'columns' are found; "
370+
"this will raise a KeyError in the future",
371+
FutureWarning)
372+
373+
self.df = df.reindex(columns=cols)
360374
self.columns = self.df.columns
361375
self.float_format = float_format
362376
self.index = index

pandas/tests/indexing/test_categorical.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,8 @@ def test_loc_listlike(self):
108108
assert_frame_equal(result, expected, check_index_type=True)
109109

110110
# not all labels in the categories
111-
pytest.raises(KeyError, lambda: self.df2.loc[['a', 'd']])
111+
with pytest.raises(KeyError):
112+
self.df2.loc[['a', 'd']]
112113

113114
def test_loc_listlike_dtypes(self):
114115
# GH 11586

pandas/tests/indexing/test_datetime.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,9 @@ def test_series_partial_set_datetime(self):
223223
Timestamp('2011-01-03')]
224224
exp = Series([np.nan, 0.2, np.nan],
225225
index=pd.DatetimeIndex(keys, name='idx'), name='s')
226-
tm.assert_series_equal(ser.loc[keys], exp, check_index_type=True)
226+
with tm.assert_produces_warning(FutureWarning,
227+
check_stacklevel=False):
228+
tm.assert_series_equal(ser.loc[keys], exp, check_index_type=True)
227229

228230
def test_series_partial_set_period(self):
229231
# GH 11497
@@ -248,5 +250,7 @@ def test_series_partial_set_period(self):
248250
pd.Period('2011-01-03', freq='D')]
249251
exp = Series([np.nan, 0.2, np.nan],
250252
index=pd.PeriodIndex(keys, name='idx'), name='s')
251-
result = ser.loc[keys]
253+
with tm.assert_produces_warning(FutureWarning,
254+
check_stacklevel=False):
255+
result = ser.loc[keys]
252256
tm.assert_series_equal(result, exp)

pandas/tests/indexing/test_iloc.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -617,7 +617,8 @@ def test_iloc_non_unique_indexing(self):
617617
expected = DataFrame(new_list)
618618
expected = pd.concat([expected, DataFrame(index=idx[idx > sidx.max()])
619619
])
620-
result = df2.loc[idx]
620+
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
621+
result = df2.loc[idx]
621622
tm.assert_frame_equal(result, expected, check_index_type=False)
622623

623624
def test_iloc_empty_list_indexer_is_ok(self):

0 commit comments

Comments
 (0)