Python Pandas Group错误'Index'对象没有属性'labels'

Uas*_*ana 9 python dataframe pandas

嗨伙计们收到这个错误:

 'Index' object has no attribute 'labels'
Run Code Online (Sandbox Code Playgroud)

回溯看起来像这样:

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'
Run Code Online (Sandbox Code Playgroud)

在运行以下代码时

df_top_f = df.groupby(['features'])['features'].count().unstack('features')
Run Code Online (Sandbox Code Playgroud)

df具有以下结构:

                                      features
             Ind                              
             0                         Doorman
             1                    Cats Allowed
             2                         Doorman
             3                    Cats Allowed
             4                    Dogs Allowed
             5                         Doorman
Run Code Online (Sandbox Code Playgroud)

df.index看起来像这样:

RangeIndex(start=0, stop=267906, step=1, name='Ind')
Run Code Online (Sandbox Code Playgroud)

看起来非常直接,但我不明白为什么我收到此错误.请帮忙

mir*_*ulo 6

也许不是最短的方法,而是一种非常直接的方法只是从索引和值显式构造一个新的DataFrame。

>>> 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
Run Code Online (Sandbox Code Playgroud)

或者,您可以通过重命名列并to_frame使用

>>> 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
Run Code Online (Sandbox Code Playgroud)

您当前的尝试无效,因为您无法在Series上拆栈单个级别的索引以将其强制为DataFrame。