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

标签 python pandas dataframe

我收到这个错误:

 'Index' object has no attribute 'labels'

回溯看起来像这样:

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'

运行以下代码时

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

df 具有以下结构:

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

df.index 看起来像这样:

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

看起来很简单,但我不明白为什么会出现此错误。

最佳答案

也许不是最短的,但一种非常直接的方法就是根据索引和值显式构造一个新的 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

或者,您可以通过重命名列和 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

您当前的尝试没有奏效,因为您无法将 Series 上的单级索引拆栈以将其强制转换为 DataFrame。

关于Python Pandas Group By 错误 'Index' 对象没有属性 'labels',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42400773/

相关文章:

python - 在远程 UNIX 机器上安装 Python

python - Pandas 根据索引与多个系列相交

python - Pandas 按时间分组,指定开始时间(非整数分钟)

python - 如何使用 pandas to_csv float_format?

python - 删除 Pandas Dataframe 中的非等效多索引行

r - 如何根据数据的整体顺序更改特定的分类变量

python - 我想要三个已安装的 PyQt DLL 目录中的哪一个?

python - 有条件地将不同 DataFrame 中的聚合列连接到新的 DataFrame 中

python - Pandas Dataframe 添加标题而不替换当前标题

python - pandas 有条件地按组移动或向前填充另一列