我试图选择数据帧子集的子集,仅选择一些列,然后对行进行过滤。
df.loc[df.a.isin(['Apple', 'Pear', 'Mango']), ['a', 'b', 'f', 'g']]
但是,我收到错误:
Passing list-likes to .loc or [] with any missing label will raise
KeyError in the future, you can use .reindex() as an alternative.
现在切片和过滤的正确方法是什么?
TL;DR:列标题名称中可能存在拼写错误或拼写错误。
这是在中引入的更改v0.21.1
,并已在docs http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#indexing-with-a-list-with-missing-labels-is-deprecated最后 -
以前,使用标签列表进行选择,其中一个或多个标签
失踪总会成功,归来NaN
对于丢失的标签。
现在将显示一个FutureWarning
。未来这将引发KeyError
(GH15747 https://github.com/pandas-dev/pandas/issues/15747)。此警告将在DataFrame
or a
Series
用于使用.loc[]
or [[]]
当使用 at 传递标签列表时
至少 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
尝试某种切片方式 -
df.loc[df.A.gt(6), ['A', 'C']]
A C
0 7.0 8
2 8.0 7
4 8.0 7
没问题。现在,尝试更换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
因此,在您的情况下,错误是由于您传递给的列标签造成的loc
。再看看他们。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)