Edward
Edward

Reputation: 4623

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

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

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?

Upvotes: 9

Views: 39083

Answers (1)

jezrael
jezrael

Reputation: 863361

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

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

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

Attribute Access in 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.min is 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.

Upvotes: 7

Related Questions