【问题标题】:Discretization into N categories with equal amounts of observations in each离散为 N 个类别,每个类别中的观测值相等
【发布时间】:2015-07-09 15:10:43
【问题描述】:

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

我在下面使用名为discretize 的请求方法创建了一个示例。 bin 和 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.split之后吗?
  • 是的,如果我先对数据进行排序,这确实有效。谢谢 - 随时提供答案。
  • 但是等等..那么我仍然需要检查来自 np.split 的数组的哪一部分来自原始数组中的每个值。
  • 最好使用array_split,这样它就不会在不相等的垃圾箱上出现问题,您可以只获取数组中的第一个/最后一个值来确定截止点吗?
  • 我未能以简单的 Python 方式做到这一点。你觉得你能告诉我怎么做吗?

标签: python numpy binning


【解决方案1】:

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

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]

【讨论】:

  • 谢谢!我已经更新了查找分箱索引的代码以满足我的要求:)
  • 不用担心,如果我的回答解决了您的问题,您可以接受并点赞
【解决方案2】:

pandas.qcut 正是这样做的。

>>>pd.qcut(range(5), 4, labels=False)

array([0, 0, 1, 2, 3]) 3])

【讨论】:

    猜你喜欢
    • 2023-01-13
    • 2019-11-20
    • 2019-11-04
    • 2017-06-21
    • 2013-05-19
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    相关资源
    最近更新 更多