Skip to main content
 首页 » 编程设计

python之Panda dataframe column cut之在均值附近更频繁地添加更多 bin

2025年05月04日25thcjp

我正在对定量变量(例如价格)进行分类,并且我想以这样一种方式对其进行分类,即在均值附近的箱子会更频繁,而在远离均值时则更少。

我已经看到有可能以线性方式 cut() 并感谢 numpy.logspace 以对数方式,但是围绕均值进行分箱似乎是无效的,我的想法到目前为止还没有奏效而且似乎效率低下.

请您参考如下方法:

您可以制作尺寸线性增加的箱子:

import numpy as np 
 
def make_progressive_bins(min_x, max_x, mean_x, num_bins=10): 
    x_rel_lim = max(mean_x - min_x, mean_x - max_x) 
    num_bins_half = num_bins // 2 
    bins_right = np.arange(0, num_bins_half + 1) 
    if num_bins % 2 == 1: 
        bins_right = bins_right + 0.5 
    bins_right = np.cumsum(bins_right) 
    bins = np.concatenate([-bins_right[bins_right > 0][::-1], bins_right]) 
    bins = bins * (float(x_rel_lim) / bins[-1]) + mean_x 
    return bins 

然后你可以像这样使用它:

import numpy as np 
import matplotlib.pyplot as plt 
 
bins = make_progressive_bins(-20, 50, 10, 15) 
plt.bar(bins - 0.1, np.ones_like(bins), 0.2)