【问题标题】:Groupby by index in Pandas在 Pandas 中按索引分组
【发布时间】:2020-12-12 09:31:05
【问题描述】:

如何按索引(1,2,3)使用 groupby(它们的顺序相同)并获得属于每个索引范围的列分数的总和?基本上我有这个:

    index  score
    1      2
    2      2
    3      2
    1      3
    2      3
    3      3

我想要什么:

    index  score  sum
    1      2      6
    2      2      9
    3      2
    1      3
    2      3
    3      3

我知道它必须是这样的:

    df = df.groupby(['Year'])['Score'].sum()

但不是一年,而是以某种方式通过索引来做到这一点?

【问题讨论】:

  • “分数”也不是唯一的列
  • df.groupby(level=0)['Score'].sum()df.groupby(level=0).sum() 其中 level=0 是索引。
  • 是的,但我需要索引组的总和,第一个 123 = 6 和第二个 123 = 9 的总和,依此类推

标签: python pandas group-by pandas-groupby


【解决方案1】:

根据 cmets,您可以 groupby 索引并在新对象 s 中返回 cumcount()。然后,您可以按这个新对象s 分组并获得sum()。我假设index 在您的示例中位于您的index 上,而不是名为index 的列上。如果是名为index的列,那么先做df = df.set_index('index')

s = df.groupby(level=0).cumcount()
df.groupby(s)['score'].sum()

0    6
1    9
Name: score, dtype: int64

如果你打印出s,那么s 看起来像这样:

    index
1    0
2    0
3    0
1    1
2    1
3    1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-31
    • 2021-12-16
    • 1970-01-01
    • 2018-08-22
    • 2015-11-04
    • 1970-01-01
    • 2021-02-02
    相关资源
    最近更新 更多