Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas Group By Error 'Index' object has no attribute 'labels'

I am getting this error:

 'Index' object has no attribute 'labels'

The traceback looks like this:

Traceback (most recent call last):

 File "<ipython-input-23-e0f428cee427>", line 1, in <module>
df_top_f = k.groupby(['features'])['features'].count().unstack('features')

 File "C:\Anaconda3\lib\site-packages\pandas\core\series.py", line 2061, in unstack
return unstack(self, level, fill_value)

File "C:\Anaconda3\lib\site-packages\pandas\core\reshape.py", line 405, in unstack
fill_value=fill_value)

File "C:\Anaconda3\lib\site-packages\pandas\core\reshape.py", line 90, in __init__
self.lift = 1 if -1 in self.index.labels[self.level] else 0

AttributeError: 'Index' object has no attribute 'labels'

While running the following code

df_top_f = df.groupby(['features'])['features'].count().unstack('features')

df has the following structure:

                                      features
             Ind                              
             0                         Doorman
             1                    Cats Allowed
             2                         Doorman
             3                    Cats Allowed
             4                    Dogs Allowed
             5                         Doorman

df.index looks like this:

RangeIndex(start=0, stop=267906, step=1, name='Ind')

Looks very straight forward, but I can't understand why I am getting this error.

like image 910
Uasthana Avatar asked Feb 22 '17 19:02

Uasthana


1 Answers

Perhaps not the shortest, but a very straightforward approach would just be to construct a new DataFrame explicitly from the index and values.

>>> grp_cnt = df.groupby(['features'])['features'].count()
>>> pd.DataFrame(dict(features=grp_cnt.index, count=grp_cnt.values))

   count      features
0      2  Cats Allowed
1      1  Dogs Allowed
2      3       Doorman

Alternatively, you could achieve a one-liner with renaming columns and to_frame using

>>> df.groupby(['features'])['features'].count().to_frame().rename(
         columns={'features':'counts'}).reset_index()

       features  counts
0  Cats Allowed       2
1  Dogs Allowed       1
2       Doorman       3

Your current attempt isn't working because you can't unstack a single level index on a Series to coerce it into a DataFrame.

like image 125
miradulo Avatar answered Oct 19 '22 22:10

miradulo