Pandas将FutureWarning切成0.21.0

Qui*_*iva 29 python filter slice pandas

我正在尝试选择数据帧子集的子集,仅选择一些列,并对行进行过滤.

df.loc[df.a.isin(['Apple', 'Pear', 'Mango']), ['a', 'b', 'f', 'g']]
Run Code Online (Sandbox Code Playgroud)

但是,我收到错误:

Passing list-likes to .loc or [] with any missing label will raise
KeyError in the future, you can use .reindex() as an alternative.
Run Code Online (Sandbox Code Playgroud)

现在切片和过滤的正确方法是什么?

cs9*_*s95 29

这是一个引入的变化v0.21.1,并在文档中详细解释-

以前,使用标签列表进行选择,其中缺少一个或多个标签将始终成功,返回NaN缺少的标签.这将显示一个FutureWarning.在未来,这将提高 KeyError(GH15747).此警告将触发a DataFrame或a Series用于.loc[][[]]在传递标签列表时至少丢失1个标签.

例如,

df

     A    B  C
0  7.0  NaN  8
1  3.0  3.0  5
2  8.0  1.0  7
3  NaN  0.0  3
4  8.0  2.0  7
Run Code Online (Sandbox Code Playgroud)

在你做的时候尝试某种切片 -

df.loc[df.A.gt(6), ['A', 'C']]

     A  C
0  7.0  8
2  8.0  7
4  8.0  7
Run Code Online (Sandbox Code Playgroud)

没问题.现在,尝试替换C不存在的列标签 -

df.loc[df.A.gt(6), ['A', 'D']]
FutureWarning: Passing list-likes to .loc or [] with any missing label will raise
KeyError in the future, you can use .reindex() as an alternative.

     A   D
0  7.0 NaN
2  8.0 NaN
4  8.0 NaN
Run Code Online (Sandbox Code Playgroud)

因此,在您的情况下,错误是由于您传递给的列标签loc.再看看他们.

  • @OrenBen-Kiki,@cs95 - 使用 JupyterLab 时,我需要使用“warnings.simplefilter('error', FutureWarning)”以获得回溯并实际查看我的代码片段导致了 FutureWarning。[参考](https://github.com/pandas-dev/pandas/issues/26329#issuecomment-491130713) (3认同)
  • 如果我*想要*在缺少任何标签的情况下引发“KeyError”怎么办?也就是说,我是否真的“想要”新行为?现在 `.loc[list_of_names]` 将给出此警告,这是我不想看到的。有什么办法可以禁用它吗? (2认同)