大家好,我收到了这个错误:
'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')
看起来非常直接但我无法理解为什么我会收到此错误。请帮忙
答案 0 :(得分:5)
也许不是最短的,但是一种非常简单的方法就是从索引和值中明确地构造一个新的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。