2017-02-22 4 views
2

こんにちはみんなを持っているが、このエラーを取得していますされていますPythonのパンダグループのインデックス 'オブジェクトが無属性のラベル "

'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

単一のレベルのインデックスをアンスタックすることはできません。何を出力として取得しようとしていますか? – miradulo

+0

@Mitchフィーチャー欄に各要素が表示された回数をちょうど数えます。 – Uasthana

+0

'.unstack( 'features')'を削除すると何が問題になりますか? _specific_出力形式を指定できますか? – miradulo

答えて

3

おそらく最短ではありませんが、非常に簡単なアプローチは、インデックスと値から明示的に新しい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 

また、あなたがするシリーズ上の単一のレベルの指標スタックを解除することはできませんので、あなたの現在の試行が動作していない

>>> 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 

を使用して列とto_frameの名前を変更してワンライナーを達成できますそれをDataFrameに変換します。

+0

はい、これは素晴らしいです。共有していただきありがとうございます! – Uasthana

+0

@Uththanaよろしくお願いします!私はもう一つの選択肢を追加しました。 – miradulo

+0

洞察をいただきありがとうございます。理解して覚えておく方がはるかに簡単です。 – Uasthana

関連する問題