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

如何为DataFrame按价格列自定义分桶并新增分桶列?

Adding Custom Binned Column to Your DataFrame

Hey there! Let's fix your issue and also optimize your approach for the specific binning rules you need (<400 = low, 401-1000 = medium, >1000 = expensive).

First: Fixing the "Adding bins to DataFrame" Problem

You already generated the bins list from your function — adding it to your DataFrame is straightforward! Just assign it directly to a new column:

# Replace df with your actual DataFrame name (like df2)
df['price_category'] = bins

Double-check that the length of your bins list matches the number of rows in your DataFrame (which it should, since you generated it from the DataFrame's column values).

Optimizing Your Binning Logic for Your Specific Rules

Your existing cut function is set up for a different binning scheme. For your target price categories, pandas and numpy have built-in functions that are more concise and efficient than manual loops (even with numba). Here are two great options:

Option 1: Using np.select() (explicit condition matching)

This is perfect for clear, discrete condition sets:

import numpy as np
import pandas as pd

# Define your conditions and corresponding labels
conditions = [
    df['price'] < 400,
    (df['price'] >= 401) & (df['price'] <= 1000),
    df['price'] > 1000
]
category_labels = ['low', 'medium', 'expensive']

# Add the new category column
df['price_category'] = np.select(conditions, category_labels)

Option 2: Using pd.cut() (built for range-based binning)

This method is purpose-built for grouping numerical values into ranges:

import pandas as pd

# Define bin ranges: (-infinity, 400], (400, 1000], (1000, +infinity)
# include_lowest=True ensures values exactly equal to 400 fall into the 'low' bin
df['price_category'] = pd.cut(
    df['price'],
    bins=[-float('inf'), 400, 1000, float('inf')],
    labels=['low', 'medium', 'expensive'],
    include_lowest=True
)

Example Output

Using either method with your input data will produce the desired result:

product_idpriceprice_category
21203expensive
4500medium
5490medium
6200low
3429medium
5321low

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 21:02:38