如何对索引大于X的所有值求和? [英] How to sum all values with index greater than X?

查看:63
本文介绍了如何对索引大于X的所有值求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个系列:

>>> s = pd.Series({1:10,2:5,3:8,4:12,5:7,6:3})
>>> s
1    10
2     5
3     8
4    12
5     7
6     3

我想对索引大于X的所有值求和. X = 3,我想得到这个:

I want to sum all the values for which the index is greater than X. So if e.g. X = 3, I want to get this:

>>> X = 3
>>> s.some_magic(X)
1    10
2     5
3     8
>3    22

我设法以这种笨拙的方式做到这一点:

I managed to do it in this rather clumsy way:

lt = s[s.index.values <= 3]
gt = s[s.index.values > 3]
gt_s = pd.Series({'>3':sum(gt)})
lt.append(gt_s)

并获得了预期的结果,但我相信应该有一种更简便,更优雅的方法...还是存在?

and got the desired result, but I believe there should be an easier and more elegant way... or is there?

推荐答案

s.groupby(np.where(s.index > 3, '>3', s.index)).sum()

或者,

s.groupby(s.index.to_series().mask(s.index > 3, '>3')).sum()
Out: 
1     10
2      5
3      8
>3    22
dtype: int64

这篇关于如何对索引大于X的所有值求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆