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. 引自官方文档
例如对这一 数据:

更改前

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

更改后

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

简单实现相同的操作

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

© Reynard 2021 - 2024