【问题标题】:How to do groupby on the basis of indexand sum in pythonpython中如何在index和sum的基础上做groupby
【发布时间】:2020-06-09 09:29:54
【问题描述】:

我的数据是

   Count
1   5
2   10
3    15
4    0
4    0
5    0
6    0
7    0
8    0
9    0
10   0
11    0
12   0
13   0
14   0
15   20

输出:

Group  Sum
0-10    30
11-20   20

按一组中的第 10 号索引分组。

【问题讨论】:

  • 请将代码和文本分开。还要用适当的输出详细说明问题。

标签: python pandas


【解决方案1】:

IIUC,你想对索引的一个函数进行分组。去做吧:

resul = df.groupby((df.index-1)//10).sum()

# adjust the index from 0,1,... to 1-10,11-20,...
resul.index = [f'{10 * i + 1}-{10 * (i+1)}' for i in resul.index]

它给出:

       Count
1-10      30
11-20     20

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 2014-10-22
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多