Pandas 已不允许使用“存在缺失标签的列表”进行索引(Indexing with list with missing labels is deprecated)

date
Apr 12, 2020
slug
pandas-index
status
Published
summary
为了 .reindex 这一方法,自 0.21.0开始,pandas 不再支持使用 .loc 或 [] 方法对存在一个或多个缺失标签的列表 (a list with one or more missing labels) 进行索引。
tags
Engineering
Data Analysis
type
Post
auth
为了 .reindex 这一方法,自 0.21.0开始,pandas 不再支持使用 .loc[] 方法对存在一个或多个缺失标签的列表 (a list with one or more missing labels) 进行索引。
📜
Starting in 0.21.0, using .loc or [] with a list with one or more missing labels, is deprecated, in favor of .reindex. 引自官方文档
例如对这一 数据:
s = pd.Series([1, 2, 3]) In [99]: s Out[99]: 0 1 1 2 2 3 dtype: int64

更改前

在此之前,我们可以直接:
s.loc[[1, 2, 3]]
得到:
Out[4]: 1 2.0 2 3.0 3 NaN dtype: float64
在上面的操作中,尽管并不存在 3 这样一个索引,pandas 还是正确选取了存在的索引并用 NaN 对不存在的索引对应的值进行填充 (上述输出中的 3 NaN)。

更改后

现在我们只能得到:
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
在这里 pandas 跑出了错误和解决指引。但是这个指引对不熟悉 pandas 的人来说并不友好,下面给出类似结果的简单操作。

简单实现相同的操作

在当前版本(>0.21.0),我们可以根据官方指引,使用 .reindex 得到相同结果:
s.reindex([1, 2, 3])
在 DataFrame 中,也类似; 若需使用列而非行,则需要指定 axis:
df.reindex([1, 2, 3], axix=1) # 列
更多样例可参见原文档
Pandas 真是更新狂魔。

Reynard © 2021 - 2024

Powered byVercel