如何将Pandas Qcut分箱值取整至最近千位且避免出现-1000?
Got it, let's work through this problem step by step. You're using pd.qcut to split your 'total' column into 10 quantile bins, aiming to round those bin edges to the nearest thousand. But when using the precision parameter, you're hitting an issue where the lower bound becomes -1000, and you want to replace that with 0 instead. Here are two straightforward solutions:
Method 1: Manually Calculate and Adjust Bin Edges First
This approach gives you full control over boundaries before applying them to your data:
Get raw quantile boundaries (without rounding):
import pandas as pd import numpy as np # Replace with your actual DataFrame df = pd.DataFrame({'total': np.random.randint(-5000, 100000, 1000)}) # Generate 10 quantile bins and extract their edges raw_bins = pd.qcut(df['total'], 10).unique().sort_values() bin_edges = [interval.left for interval in raw_bins] + [raw_bins[-1].right]Round edges to the nearest thousand:
Usenp.aroundwith a negative precision to target thousand-level rounding:rounded_edges = np.around(np.array(bin_edges), -3)Replace negative edges with 0:
rounded_edges[rounded_edges < 0] = 0Remove duplicates and apply to your data:
final_edges = np.unique(rounded_edges) df['binned_total'] = pd.cut(df['total'], bins=final_edges, include_lowest=True)Note: If you need to preserve qcut's equal-quantile property, you can use the adjusted edges with
pd.qcutinstead ofpd.cut—just be aware duplicates might force minor adjustments to maintain bin counts.
Method 2: Adjust Existing qcut Bins Directly
If you already ran qcut with rounding and just need to fix the -1000 edge, modify the existing intervals:
Run qcut with thousand-level rounding:
df['binned_total'] = pd.qcut(df['total'], 10, precision=-3)Replace negative left boundaries with 0:
Useapplyto tweak each interval's left edge to be at least 0:df['binned_total'] = df['binned_total'].apply( lambda interval: pd.Interval( left=max(interval.left, 0), right=interval.right, closed=interval.closed ) )
This keeps your quantile-based binning intact while ensuring no negative lower bounds—any bin that started with -1000 will now start at 0.
内容的提问来源于stack exchange,提问作者Iwan

