soungalo - 2 months ago 6x

Python Question

Let's say I have this series:

`>>> 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

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?

Answer

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

Or,

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

Source (Stackoverflow)

Comments