如何为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_id | price | price_category |
|---|---|---|
| 2 | 1203 | expensive |
| 4 | 500 | medium |
| 5 | 490 | medium |
| 6 | 200 | low |
| 3 | 429 | medium |
| 5 | 321 | low |
内容的提问来源于stack exchange,提问作者user12625679

