python 中的聚合数据帧索引
Aggregate dataframe indices in python
我想用 groupby 函数聚合数据帧的索引。
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 的内置函数,但是,我找不到聚合索引的方法。您愿意为这个问题提供任何提示或解决方案吗?
我想你可以先将 index
的顺序更改为 [::-1]
,然后 groupby
and apply
index
to list
. Last 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
我想用 groupby 函数聚合数据帧的索引。
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 的内置函数,但是,我找不到聚合索引的方法。您愿意为这个问题提供任何提示或解决方案吗?
我想你可以先将 index
的顺序更改为 [::-1]
,然后 groupby
and apply
index
to list
. Last 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