【问题标题】:Split an array into data based on bins returned by numpy histogram根据 numpy histogram 返回的 bin 将数组拆分为数据
【发布时间】:2018-12-17 21:24:52
【问题描述】:

我有一个数组x,其数据如下:[3.1, 3.0, 3.3, 3.5, 3.8, 3.75, 4.0] 等。 我有另一个变量 y 对应的 0 和 1 [0, 1, 0] 我想从那个新的单独数组中得到分割

freq, bins = np.histogram(X, 5)

这让我知道每个垃圾箱的截止值。但我如何真正获得这些数据?例如,如果我有两个箱(3 到 3.5 和 3.5 到 4),我想要两个得到两个数组作为回报,例如 [3.1, 3.2, 3.4, ...] 和 [3.6, 3.7, 4, ... ]。另外,我希望变量y 以相同的方式被破坏和排序。

总结:我正在寻找将x 分解为具有相应y 值的箱的代码。

我考虑过使用bins 变量做一些事情,但我不确定如何根据截止值拆分数据。感谢您的帮助。

如果我绘制 X 的正常直方图,我会得到:

使用代码:

d=plt.hist(X, 5, facecolor='blue', alpha=0.5)

工作代码:

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)


def getLists(a, b, bin_obj):
    index_list = []
    for left, right in pairwise(bin_obj):
        indices = np.where((a >= left) & (a < right))
        index_list += [indices[0]]
    X_ret = [a[i] for i in index_list]
    Y_ret = [b[i] for i in index_list]
    return (X_ret, Y_ret)
freq, bins = np.histogram(X[:, 0], 5)

Xnew, Ynew = getLists(X[:, 0], Y, bins)

【问题讨论】:

  • x中会不会有重复值?
  • 是的,X 可以是 0 到 4 之间的任何值,但更可能是 3 到 4 之间。重复值可能而且将会发生。

标签: python histogram frequency bins


【解决方案1】:

标准库中有一些 Python 函数 defined

from itertools import tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

它可以帮助您遍历您的 bin 并获取元素的索引。

for left, right in pairwise(bins):
    indices = np.where((x >= left) & (x < right))
    print(x[indices], y[indices])

【讨论】:

  • 打印语句不起作用,因为索引包含索引以外的一些其他数据。我把工作代码放在我的问题中。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-30
  • 1970-01-01
  • 2016-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多