You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The idiomatic way to achieve selecting potentially not-found elmenents is via ``.reindex()``. See also the section on :ref:`reindexing <basics.reindexing>`.
729
+
730
+
.. ipython:: python
731
+
732
+
s.reindex([1, 2, 3])
733
+
734
+
Alternatively, if you want to select only *valid* keys, the following is idiomatic; furthermore this is more efficient, and is guaranteed to preserve the dtype of the selection.
735
+
736
+
.. ipython:: python
737
+
738
+
keys = [1, 2, 3]
739
+
s.loc[s.index & keys]
740
+
741
+
Having a duplicated index will raise for a ``.reindex()``:
742
+
743
+
.. ipython:: python
744
+
745
+
s = pd.Series(np.arange(4), index=['a', 'a', 'b', 'c'])
746
+
747
+
.. code-block:: python
748
+
749
+
In [17]: s.reindex(['c', 'd'])
750
+
ValueError: cannot reindex from a duplicate axis
751
+
752
+
The idiomatic expression again allows this operation to proceed
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
+
See the :ref:`deprecation docs <indexing.deprecate_loc_reindex_listlike>`.
169
+
170
+
171
+
.. ipython:: python
172
+
173
+
s = Series([1, 2, 3])
174
+
s
175
+
176
+
Previous Behavior
177
+
178
+
.. code-block:: ipython
179
+
180
+
181
+
In [4]: s.loc[[1, 2, 3]]
182
+
Out[4]:
183
+
1 2.0
184
+
2 3.0
185
+
3 NaN
186
+
dtype: float64
187
+
188
+
189
+
Current Behavior
190
+
191
+
In [4]: s.loc[[1, 2, 3]]
192
+
Passing list-likes to .loc with any non-matching elements will raise
193
+
KeyError in the future, you can use .reindex() as an alternative.
0 commit comments