python - 离散化为 N 个类别,每个类别具有相同数量的观察值

标签 python numpy binning

我有一个 1-5 范围内的非正态分布的 numpy float 数组。我想找到 N-1 截断值,将这些值分成 N 个 bin,其中每个 bin 具有相同数量的观察值。平均分配并不总是可能的,但尽可能接近将是完美的。它将用于约 1000 次观察。

我在下面创建了一个示例,其中请求的方法名为 discretize。 bins 和 cutoffs 应该按升序排列。

import numpy as np
import random

dat = np.hstack(([random.uniform(1,5) for i in range(10)], [random.uniform(4,5) for i in range(5)]))
print dat # [4.0310121   3.53599004  1.7687312   4.94552008  2.00898982  4.5596209, ...

discrete_dat, cutoffs = discretize(dat, bins=3)
print cutoffs # 2.2, 3.8
print discrete_dat # 3, 2, 1, 3, 1, 3, ...

最佳答案

好吧,我很快就破解了这个,所以它使用了 np.array_split因此对于大小不等的 bins 它不会呕吐,这首先对数据进行排序,然后执行计算以拆分并返回截止值:

import random
import numpy as np

dat = np.arange(1,13)/2.0

def discretize(data, bins):
    split = np.array_split(np.sort(data), bins)
    cutoffs = [x[-1] for x in split]
    cutoffs = cutoffs[:-1]
    discrete = np.digitize(data, cutoffs, right=True)
    return discrete, cutoffs

discrete_dat, cutoff = discretize(dat, 3)
print "dat: {}".format(dat)
print "discrete_dat: {}".format(discrete_dat)
print "cutoff: {}".format(cutoff)

>> dat: [ 0.5  1.   1.5  2.   2.5  3.   3.5  4.   4.5  5.   5.5  6. ]
>> discrete_dat: [0 0 0 0 1 1 1 1 2 2 2 2]
>> cutoff: [2.0, 4.0]

关于python - 离散化为 N 个类别,每个类别具有相同数量的观察值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31321510/

相关文章:

python - 为什么使用 pywebsocket 创建的 websocket 会自动关闭?

python - 如何通过调整 RGB 值来编写自定义灰度滤镜?

python - 如何将 numpy 数组转换为形式 ((value0, row0, column0), (value1, row0, column1)...)?

python-3.x - 在另一个数组中高效查找下一个更大的

python - 快速分类(分箱)

Python 数据抓取

python - 高级数组/数据帧切片(numpy/pandas)

python - 在Python中对可变长度列表进行分箱

R - hist(XX, plot=FALSE)$count 的更快替代品

python - 将 DCT 系数可视化为图像的好方法