如何在Python Pandas中按指定数值范围分组统计记录数
Hey there! Let's walk through how to get the exact count you need for those value ranges using pandas. Here's a step-by-step breakdown:
Step 1: Set up your DataFrame
First, we'll create the DataFrame you provided (if you haven't already):
import pandas as pd df = pd.DataFrame({ 'name': ['a', 'b', 'c', 'd', 'e', 'f', 'g'], 'value': [100, 200, 150, 300, 400, 200, 100] })
Step 2: Define ranges and group the data
We'll use pd.cut() to bin the value column into your specified ranges, then count how many records fall into each bin. We'll make sure the boundaries are handled correctly (including the lower end of each range):
# Define the bins and corresponding category labels bins = [0, 100, 200, float('inf')] labels = ['0-100', '100-200', '超过200'] # Group by the bins and count records count_result = df['value'].groupby( pd.cut(df['value'], bins=bins, labels=labels, include_lowest=True) ).count().reset_index() # Rename columns to match your desired output count_result.columns = ['category', 'count']
Step 3: View the result
When you print count_result, you'll get:
category count 0 0-100 2 1 100-200 3 2 超过200 2
Quick note on the expected count
I noticed your expected output shows 3 records for "超过200", but based on the DataFrame you shared, only records d (300) and e (400) fall into that range. If you need the count to be 3, double-check if there's an extra record in your dataset or adjust the bin boundaries (e.g., move 200 into the "超过200" category instead of "100-200").
内容的提问来源于stack exchange,提问作者Sai Rajesh

