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

如何为CSV数据设置条件分箱范围以绘制直方图?

如何为Pandas直方图设置条件分箱范围?

没问题,要实现条件分箱其实很简单——Pandas的hist()方法本身就支持传入自定义的分箱区间列表,不管是手动指定的规则,还是根据数据动态生成的条件分箱,都能轻松实现。下面我给你两种常见的实现方式:

1. 手动指定条件分箱区间

如果你的分箱规则是明确的(比如想把数据分成[0,20), [20,50), [50,80), [80,100]这类非均匀区间),直接把分箱边界做成列表传给bins参数就行。修改后的代码如下:

import pandas as pd
import matplotlib.pyplot as plt

class CreateHistogram():
    def __init__(self, csv_file):
        self.csv_file = csv_file
    
    def load_csv(self, custom_bins=None):
        # 保留默认分箱(原固定区间,可选)
        if custom_bins is None:
            custom_bins = range(0, 100, 10)
        
        tp_data = pd.read_csv(self.csv_file)
        dataframe = tp_data['tp']  # 直接取列更简洁,无需额外套DataFrame
        
        # 用自定义分箱绘制直方图,加edgecolor让区间边界更清晰
        dataframe.hist(bins=custom_bins, edgecolor='black')
        plt.xlabel('TP Value')
        plt.ylabel('Frequency')
        plt.title('Histogram with Custom Conditional Bins')
        plt.show()
        
        return tp_data

# 使用示例:传入自定义条件分箱
hist_maker = CreateHistogram('your_data.csv')
# 比如设置条件分箱:0-20,20-50,50-80,80-100
hist_maker.load_csv(custom_bins=[0,20,50,80,100])

2. 根据数据动态生成条件分箱

如果需要根据数据的特征(比如分位数、均值、特定阈值)动态生成分箱,可以先计算分箱边界再传入。举个例子,根据数据的四分位数来划分区间:

import pandas as pd
import matplotlib.pyplot as plt

class CreateHistogram():
    def __init__(self, csv_file):
        self.csv_file = csv_file
    
    def load_csv_with_dynamic_bins(self):
        tp_data = pd.read_csv(self.csv_file)
        dataframe = tp_data['tp']
        
        # 根据数据统计值生成条件分箱
        q25 = dataframe.quantile(0.25)
        q50 = dataframe.median()
        q75 = dataframe.quantile(0.75)
        max_val = dataframe.max()
        
        # 构建动态分箱:0-25%分位数,25%-中位数,中位数-75%分位数,75%-最大值
        dynamic_bins = [0, q25, q50, q75, max_val]
        
        dataframe.hist(bins=dynamic_bins, edgecolor='black')
        plt.xlabel('TP Value')
        plt.ylabel('Frequency')
        plt.title('Histogram with Dynamic Conditional Bins')
        plt.show()
        
        return tp_data

补充说明

  • 核心逻辑:给bins参数传入有序数值列表即可,列表元素就是分箱的边界(比如[a,b,c]会生成[a,b)、[b,c)两个左闭右开的区间)。
  • 若需要调整区间闭合方向,可以配合right=False参数(默认是左闭右开)。

内容的提问来源于stack exchange,提问作者Pankaj Dhawan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:15:11