2016-09-22 95 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