python中的聚合数据框索引
问题描述:
我想聚合一个数据框的索引与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一些内置的功能,但是,我不能”吨找到一种方法来汇总指数。你想为这个问题提供任何提示或解决方案吗?
答
我觉得你可以先通过[::-1]
改变index
顺序,然后groupby
和apply
index
到list
。最后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
所以你放弃了'tag'和'count'列? – IanS
@IanS好的。对于这个问题,这些列是无用的。我只是强调数据是一个数据框。 – SUNDONG