Skip to content Skip to sidebar Skip to footer

How To Sum All Values With Index Greater Than X?

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 f

Solution 1:

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

Solution 2:

Here's a possible solution:

import pandas as pd

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

print s[iv <= 3].append(pd.Series({'>3': s[iv > 3].sum()}))

Post a Comment for "How To Sum All Values With Index Greater Than X?"