You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python Pandas中按指定数值范围分组统计记录数

Solution to Count Records by Value Ranges in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:23:55