Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 793
Edward Avatar asked Dec 22 '16 15:12

Edward


1 Answers

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.

like image 137
jezrael Avatar answered Oct 31 '22 11:10

jezrael