Python Pandas按错误分组“索引"对象没有属性“标签" [英] Python Pandas Group By Error 'Index' object has no attribute 'labels'
本文介绍了Python Pandas按错误分组“索引"对象没有属性“标签"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,出现此错误:
'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看起来像这样:
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. Please help
推荐答案
也许不是最短的方法,但是一种非常直接的方法只是从索引和值显式构造一个新的DataFrame.
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
您当前的尝试不起作用,因为您无法在Series上拆开单个级别的索引以将其强制转换为DataFrame.
Your current attempt isn't working because you can't unstack a single level index on a Series to coerce it into a DataFrame.
这篇关于Python Pandas按错误分组“索引"对象没有属性“标签"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文