如何在Python中基于索引执行groupby并求和:按索引10分组
Got it, let's walk through how to group your Count column by the specified index ranges (0-10 and 11-20) and calculate the sums—super straightforward with pandas, which is the standard tool for this kind of data manipulation.
Step 1: Set up your sample data
First, let's recreate your dataset so you can test the code directly:
import pandas as pd # Build the Count data as described count_values = { 1: 5, 2: 10, 3: 15, **{i: 0 for i in range(4, 11)}, # Indexes 4-10: 0 **{i: 0 for i in range(11, 15)}, # Indexes 11-14: 0 15: 20 } # Convert to a pandas Series (we can leave missing indexes as-is since their value is 0) count_series = pd.Series(count_values)
Step 2: Group and sum using two simple methods
Method 1: Lambda function for quick binary grouping
If you only have two simple ranges, a lambda function in groupby is the quickest way:
# Group by index range and sum result = count_series.groupby(lambda idx: '0-10' if idx <= 10 else '11-20').sum() print(result)
This will output exactly what you need:
0-10 30 11-20 20 dtype: int64
Method 2: pd.cut for more flexible intervals
If you ever need to add more index ranges later, pd.cut is more scalable. We'll define bins to map indexes to groups:
# Define bins (use -1 to ensure index 0 is included, since pd.cut is left-open by default) bins = [-1, 10, 20] # Names for our groups group_labels = ['0-10', '11-20'] # Group and sum result = count_series.groupby(pd.cut(count_series.index, bins=bins, labels=group_labels)).sum() print(result)
This gives the same output as the first method, but it's easier to adjust if you need to split into more ranges (like 0-5, 6-10, 11-15, etc.) later.
Why this works
- For the lambda method: We're checking each index directly—if it's ≤10, it goes to the '0-10' group, else to '11-20'. Missing indexes (like 0, 16-20) are treated as having a value of 0, so they don't affect the sum.
- For
pd.cut: We create bins that capture the exact index ranges we want. The-1in the first bin ensures index 0 is included (sincepd.cutdefaults to left-exclusive, right-inclusive intervals).
内容的提问来源于stack exchange,提问作者Anand

