Data | Indexing with list with missing labels is deprecated in Pandas

date
Apr 12, 2020
slug
index-missing-label-deprecated-pandas
status
Published
summary
For .reindex , from 0.21.0, .loc or [] are not allowed to index with a list with one or more missing labels in Pandas
tags
Academic
Data Analysis
Python
Pandas
type
Post
For .reindex , from 0.21.0, .loc or [] are not allowed to index with a list with one or more missing labels in Pandas
📜
Starting in 0.21.0, using .loc or [] with a list with one or more missing labels, is deprecated, in favor of .reindex.
i.e.
s = pd.Series([1, 2, 3])
In [99]: s
Out[99]:
0    1
1    2
2    3
dtype: int64

Before

Simple:
s.loc[[1, 2, 3]]
Get:
Out[4]:
1    2.0
2    3.0
3    NaN
dtype: float64

After

Now, we only get:
In [4]: s.loc[[1, 2, 3]]
Passing list-likes to .loc with any non-matching elements will raise
KeyError in the future, you can use .reindex() as an alternative.
See the documentation here:
https://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reindex-listlike
Out[4]:
1    2.0
2    3.0
3    NaN
dtype: float64

Similar behavior in a simple way

In current version (>0.21.0), we can use .reindex to get expected result as before, according to the official document:
s.reindex([1, 2, 3])
In DataFrame, similar:
df.reindex([1, 2, 3], axix=1) # 列
More examples are listed here
Pandas updates a lot~~~ : (

RSS | Reynard © 2021 - 2023

Powered byVercel