按索引选择行-熊猫位置-任何缺少的标签

时间:2020-10-12 09:30:57

标签: python pandas indexing label loc

Python版本3.8.5 /熊猫版本1.1.2

要显示从0到99的索引行,我使用了

df[df.col_1 > 60].loc[range(0,99), 'col_2']

但是我收到了此错误消息

KeyError:“将带有任何缺失标签的列表式传递给.loc或[]是 不再受支持。缺少以下标签:Int64Index([ 1,3,4,6,7,\ n ... \ n 95,96,97,98, 99],\ n dtype ='int64',长度= 72)。看到 https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#deprecate-loc-reindex-listlike"

作为替代方案,我有一个适用于我的情况的选项:

df[df.col_1 > 2].loc[0:4, 'col_2']

我听说新的熊猫版本不再接受它。 感谢您的确认。

3 个答案:

答案 0 :(得分:1)

我认为这里最好用&链接2个蒙版,然后传递给一个loc

df[(df.col_1 > 60) & df.index.isin(range(99)), 'col_2']

答案 1 :(得分:0)

由于过滤器df.col1> 60,某些索引在数据帧中不存在,但是u在loc中给出了range(0,99)的自变量,因此没有出现,则会引发错误。如果你想要100个元素。 用这个

df[df.col_1 > 60].iloc[range(0,99), 'col_2']

如果您想使用第100个元素,请尝试以下操作:

df=df.loc[range(99), ["col_1",'col_2']]
df[df[loc_1]>60].drop("col_1",axis=1)

答案 2 :(得分:0)

按以下方式尝试。

在这里,我们没有考虑range(99)的所有值,而是采用了交集。

df[df.col_1 > 60].loc[df[df.col_1 > 60].index.intersection(range(99)), 'col_2']