Skip to content

Commit e5f80e3

Browse files
committed
API: warning to raise KeyError in the future if not all elements of a list are selected via .loc
closes #15747
1 parent 870b6a6 commit e5f80e3

File tree

13 files changed

+220
-56
lines changed

13 files changed

+220
-56
lines changed

doc/source/whatsnew/v0.21.0.txt

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,57 @@ We have updated our minimum supported versions of dependencies (:issue:`15206`,
158158
| Bottleneck | 1.0.0 | |
159159
+--------------+-----------------+----------+
160160

161+
.. _whatsnew_0210.api_breaking.loc:
162+
163+
.loc will warn if not all keys are found with a list indexer
164+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
165+
166+
Selecting at least 1 valid key with a list-like indexer would succeed and return ``NaN`` for non-found elements.
167+
This is exactly the function of ``.reindex()``. This will now show a ``FutureWarning`` message; in the future this will raise ``KeyError`` (:issue:`15747`)
168+
169+
.. ipython:: python
170+
171+
s = Series([1, 2, 3])
172+
s
173+
174+
Selection with all keys found is unchanged.
175+
176+
.. ipython:: python
177+
178+
s.loc[[1, 2]]
179+
180+
Previously Behavior
181+
182+
.. code-block:: ipython
183+
184+
185+
In [4]: s.loc[[1, 2, 3]]
186+
Out[4]:
187+
1 2.0
188+
2 3.0
189+
3 NaN
190+
dtype: float64
191+
192+
193+
Current Behavior
194+
195+
In [4]: s.loc[[1, 2, 3]]
196+
/Users/jreback/miniconda3/envs/pandas/bin/ipython:1: FutureWarning: passing list-likes to .loc with any non-matching elements will raise
197+
KeyError in the future, you can use .reindex() as an alternative
198+
#!/Users/jreback/miniconda3/envs/pandas/bin/python
199+
Out[4]:
200+
1 2.0
201+
2 3.0
202+
3 NaN
203+
dtype: float64
204+
205+
The idiomatic way to achieve selecting potentially not-found elmenents if via ``.reindex()``
206+
207+
.. ipython:: python
208+
209+
s.reindex([1, 2, 3])
210+
211+
161212
.. _whatsnew_0210.api_breaking.pandas_eval:
162213

163214
Improved error handling during item assignment in pd.eval

pandas/core/indexing.py

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1416,12 +1416,32 @@ def _has_valid_type(self, key, axis):
14161416
if isinstance(key, tuple) and isinstance(ax, MultiIndex):
14171417
return True
14181418

1419-
# TODO: don't check the entire key unless necessary
1420-
if (not is_iterator(key) and len(key) and
1421-
np.all(ax.get_indexer_for(key) < 0)):
1419+
if not is_iterator(key) and len(key):
14221420

1423-
raise KeyError("None of [%s] are in the [%s]" %
1424-
(key, self.obj._get_axis_name(axis)))
1421+
# True indicates missing values
1422+
missing = ax.get_indexer_for(key) < 0
1423+
1424+
if np.any(missing):
1425+
if len(key) == 1 or np.all(missing):
1426+
raise KeyError("None of [%s] are in the [%s]" %
1427+
(key, self.obj._get_axis_name(axis)))
1428+
1429+
else:
1430+
1431+
# we skip the warning on Categorical/Interval
1432+
# as this check is actually done (check for
1433+
# non-missing values), but a bit later in the
1434+
# code, so we want to avoid warning & then
1435+
# just raising
1436+
if not (ax.is_categorical() or ax.is_interval()):
1437+
warnings.warn(
1438+
"passing list-likes to .loc with "
1439+
"any non-matching elements will raise\n"
1440+
"KeyError in the future, "
1441+
"you can use .reindex() as an alternative",
1442+
FutureWarning, stacklevel=5)
1443+
1444+
return True
14251445

14261446
return True
14271447

pandas/io/formats/excel.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -353,7 +353,15 @@ def __init__(self, df, na_rep='', float_format=None, cols=None,
353353
self.styler = None
354354
self.df = df
355355
if cols is not None:
356-
self.df = df.loc[:, cols]
356+
357+
# all missing, raise
358+
if not len(Index(cols) & df.columns):
359+
raise KeyError
360+
361+
# 1 missing is ok
362+
# TODO(jreback)k this should raise
363+
# on *any* missing columns
364+
self.df = df.reindex(columns=cols)
357365
self.columns = self.df.columns
358366
self.float_format = float_format
359367
self.index = index

pandas/tests/indexing/test_categorical.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,8 @@ def test_loc_listlike(self):
111111
assert_frame_equal(result, expected, check_index_type=True)
112112

113113
# not all labels in the categories
114-
pytest.raises(KeyError, lambda: self.df2.loc[['a', 'd']])
114+
with pytest.raises(KeyError):
115+
self.df2.loc[['a', 'd']]
115116

116117
def test_loc_listlike_dtypes(self):
117118
# GH 11586

pandas/tests/indexing/test_datetime.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ 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+
tm.assert_series_equal(ser.reindex(keys), exp, check_index_type=True)
227227

228228
def test_series_partial_set_period(self):
229229
# GH 11497
@@ -248,5 +248,5 @@ def test_series_partial_set_period(self):
248248
pd.Period('2011-01-03', freq='D')]
249249
exp = Series([np.nan, 0.2, np.nan],
250250
index=pd.PeriodIndex(keys, name='idx'), name='s')
251-
result = ser.loc[keys]
251+
result = ser.reindex(keys)
252252
tm.assert_series_equal(result, exp)

pandas/tests/indexing/test_iloc.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -588,7 +588,8 @@ def test_iloc_non_unique_indexing(self):
588588
expected = DataFrame(new_list)
589589
expected = pd.concat([expected, DataFrame(index=idx[idx > sidx.max()])
590590
])
591-
result = df2.loc[idx]
591+
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
592+
result = df2.loc[idx]
592593
tm.assert_frame_equal(result, expected, check_index_type=False)
593594

594595
def test_iloc_empty_list_indexer_is_ok(self):

pandas/tests/indexing/test_indexing.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,8 @@ def test_dups_fancy_indexing(self):
176176
'test1': [7., 6, np.nan],
177177
'other': ['d', 'c', np.nan]}, index=rows)
178178

179-
result = df.loc[rows]
179+
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
180+
result = df.loc[rows]
180181
tm.assert_frame_equal(result, expected)
181182

182183
# see GH5553, make sure we use the right indexer
@@ -186,7 +187,8 @@ def test_dups_fancy_indexing(self):
186187
'other': [np.nan, np.nan, np.nan,
187188
'd', 'c', np.nan]},
188189
index=rows)
189-
result = df.loc[rows]
190+
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
191+
result = df.loc[rows]
190192
tm.assert_frame_equal(result, expected)
191193

192194
# inconsistent returns for unique/duplicate indices when values are
@@ -203,20 +205,23 @@ def test_dups_fancy_indexing(self):
203205

204206
# GH 4619; duplicate indexer with missing label
205207
df = DataFrame({"A": [0, 1, 2]})
206-
result = df.loc[[0, 8, 0]]
208+
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
209+
result = df.loc[[0, 8, 0]]
207210
expected = DataFrame({"A": [0, np.nan, 0]}, index=[0, 8, 0])
208211
tm.assert_frame_equal(result, expected, check_index_type=False)
209212

210213
df = DataFrame({"A": list('abc')})
211-
result = df.loc[[0, 8, 0]]
214+
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
215+
result = df.loc[[0, 8, 0]]
212216
expected = DataFrame({"A": ['a', np.nan, 'a']}, index=[0, 8, 0])
213217
tm.assert_frame_equal(result, expected, check_index_type=False)
214218

215219
# non unique with non unique selector
216220
df = DataFrame({'test': [5, 7, 9, 11]}, index=['A', 'A', 'B', 'C'])
217221
expected = DataFrame(
218222
{'test': [5, 7, 5, 7, np.nan]}, index=['A', 'A', 'A', 'A', 'E'])
219-
result = df.loc[['A', 'A', 'E']]
223+
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
224+
result = df.loc[['A', 'A', 'E']]
220225
tm.assert_frame_equal(result, expected)
221226

222227
# GH 5835
@@ -227,7 +232,8 @@ def test_dups_fancy_indexing(self):
227232
expected = pd.concat(
228233
[df.loc[:, ['A', 'B']], DataFrame(np.nan, columns=['C'],
229234
index=df.index)], axis=1)
230-
result = df.loc[:, ['A', 'B', 'C']]
235+
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
236+
result = df.loc[:, ['A', 'B', 'C']]
231237
tm.assert_frame_equal(result, expected)
232238

233239
# GH 6504, multi-axis indexing

pandas/tests/indexing/test_loc.py

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -152,12 +152,15 @@ def test_loc_getitem_label_list(self):
152152
[Timestamp('20130102'), Timestamp('20130103')],
153153
typs=['ts'], axes=0)
154154

155+
def test_loc_getitem_label_list_with_missing(self):
155156
self.check_result('list lbl', 'loc', [0, 1, 2], 'indexer', [0, 1, 2],
156157
typs=['empty'], fails=KeyError)
157-
self.check_result('list lbl', 'loc', [0, 2, 3], 'ix', [0, 2, 3],
158-
typs=['ints', 'uints'], axes=0, fails=KeyError)
159-
self.check_result('list lbl', 'loc', [3, 6, 7], 'ix', [3, 6, 7],
160-
typs=['ints', 'uints'], axes=1, fails=KeyError)
158+
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
159+
self.check_result('list lbl', 'loc', [0, 2, 3], 'ix', [0, 2, 3],
160+
typs=['ints', 'uints'], axes=0, fails=KeyError)
161+
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
162+
self.check_result('list lbl', 'loc', [3, 6, 7], 'ix', [3, 6, 7],
163+
typs=['ints', 'uints'], axes=1, fails=KeyError)
161164
self.check_result('list lbl', 'loc', [4, 8, 10], 'ix', [4, 8, 10],
162165
typs=['ints', 'uints'], axes=2, fails=KeyError)
163166

@@ -249,7 +252,7 @@ def test_loc_to_fail(self):
249252
pytest.raises(KeyError, lambda: s.loc[['4']])
250253

251254
s.loc[-1] = 3
252-
result = s.loc[[-1, -2]]
255+
result = s.reindex([-1, -2])
253256
expected = Series([3, np.nan], index=[-1, -2])
254257
tm.assert_series_equal(result, expected)
255258

@@ -277,6 +280,23 @@ def f():
277280

278281
pytest.raises(KeyError, f)
279282

283+
def test_loc_getitem_list_with_fail(self):
284+
# 15747
285+
# should KeyError if *any* missing labels
286+
287+
s = Series([1, 2, 3])
288+
289+
s.loc[[2]]
290+
291+
with pytest.raises(KeyError):
292+
s.loc[[3]]
293+
294+
# a non-match and a match
295+
with tm.assert_produces_warning(FutureWarning):
296+
expected = s.loc[[2, 3]]
297+
result = s.reindex([2, 3])
298+
tm.assert_series_equal(result, expected)
299+
280300
def test_loc_getitem_label_slice(self):
281301

282302
# label slices (with ints)

0 commit comments

Comments
 (0)