2016-09-22 65 views
1

我想聚合一個數據框的索引與groupby函數。python中的聚合數據框索引

 word count 
0 a  3 
1 the 5 
2 a  3 
3 an 2 
4 the 1 

我要的是一個pd.Series其中包括列表的索引(降序),

word 
a  [2, 0] 
an   [3] 
the  [4, 1] 

我試着GROUPBY一些內置的功能,但是,我不能」噸找到一種方法來彙總指數。你想爲這個問題提供任何提示或解決方案嗎?

+0

所以你放棄了'tag'和'count'列? – IanS

+0

@IanS好的。對於這個問題,這些列是無用的。我只是強調數據是一個數據框。 – SUNDONG

回答

2

我覺得你可以先通過[::-1]改變index順序,然後groupbyapplyindexlist。最後sort_index

print (df[::-1].groupby('word', sort=False).apply(lambda x: x.index.tolist()).sort_index()) 
word 
a  [2, 0] 
an  [3] 
the [4, 1] 
dtype: object 

另一個類似的解決方案:

print (df.sort_index(ascending=False) 
     .groupby('word', sort=False) 
     .apply(lambda x: x.index.tolist()) 
     .sort_index()) 
word 
a  [2, 0] 
an  [3] 
the [4, 1] 
dtype: object 
+0

非常感謝。我需要習慣lambda函數! – SUNDONG

+0

很高興能幫到你! – jezrael