无法使用这些索引器对 <class 'pandas.indexes.range.RangeIndex'> 进行切片索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41287058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:39:40  来源:igfitidea点击:

cannot do slice indexing on <class 'pandas.indexes.range.RangeIndex'> with these indexers

python-3.xpandas

提问by Edward

It's very strange error to my mind

在我看来这是一个非常奇怪的错误

import numpy as np
import pandas as pd
df = pd.DataFrame({'head': [1, 1,2,2,1,3,2,3,1,1,1,2, 3,3], 
                  'appraisal': [1,2,1,3,1,4,1,5,1,1,2,3,4,5]})

then

然后

df.loc[df.head, 'appraisal'].mean()

and

TypeError: cannot do slice indexing on <class 'pandas.indexes.range.RangeIndex'> with these indexers

But if i change 'head' to for ample 'head_id' it works correct

但是,如果我将“head”更改为足够的“head_id”,则它可以正常工作

df = pd.DataFrame({'head_id': [1, 1,2,2,1,3,2,3,1,1,1,2, 3,3], 
                  'appraisal': [1,2,1,3,1,4,1,5,1,1,2,3,4,5]})
df.loc[df.head_id, 'appraisal'].mean()
2.0

what's wrong?

怎么了?

采纳答案by jezrael

headis function of pandas, so need [], same is impossible use df.sum, df.min- but works df['sum'], df['mean']:

head是Pandas的功能,所以需要[],同样是不可能使用的df.sumdf.min- 但有效df['sum']df['mean']

df.loc[df['head'], 'appraisal'].mean()

#if change 'head' to 'head1' it works
df.loc[df.head1, 'appraisal'].mean()

Attribute Accessin docs:

文档中的属性访问

You can use this access only if the index element is a valid python identifier, e.g. s.1 is not allowed. See here for an explanation of valid identifiers.

The attribute will not be available if it conflicts with an existing method name, e.g. s.minis not allowed.

Similarly, the attribute will not be available if it conflicts with any of the following list: index, major_axis, minor_axis, items, labels.

In any of these cases, standard indexing will still work, e.g. s['1'], s['min'], and s['index'] will access the corresponding element or column.

The Series/Panel accesses are available starting in 0.13.0.

仅当 index 元素是有效的 python 标识符时才可以使用此访问, egs1 是不允许的。有关有效标识符的说明,请参见此处。

如果该属性与现有方法名称冲突,则该属性将不可用,例如不允许使用s.min

同样,如果该属性与以下任何列表冲突,则该属性将不可用:index、major_axis、minor_axis、items、labels。

在任何这些情况下,标准索引仍然有效,例如 s['1']、s['min'] 和 s['index'] 将访问相应的元素或列。

系列/面板访问从 0.13.0 开始可用。