根据 numpy 直方图返回的 bins 将数组拆分为数据
Split an array into data based on bins returned by numpy histogram
我有一个数组 x
,其中包含如下数据:[3.1, 3.0, 3.3, 3.5, 3.8, 3.75, 4.0] 等。
我有另一个变量 y
对应的 0s 和 1s [0, 1, 0]
我想从那个新的单独数组中得到 divided
freq, bins = np.histogram(X, 5)
这让我知道每个箱子的截止值。但是我实际上如何获得这些数据呢?例如,如果我有两个 bin(3 到 3.5 和 3.5 到 4),我想要两个在 return 中得到两个数组,像这样 [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)
标准库中有一些 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])
我有一个数组 x
,其中包含如下数据:[3.1, 3.0, 3.3, 3.5, 3.8, 3.75, 4.0] 等。
我有另一个变量 y
对应的 0s 和 1s [0, 1, 0]
我想从那个新的单独数组中得到 divided
freq, bins = np.histogram(X, 5)
这让我知道每个箱子的截止值。但是我实际上如何获得这些数据呢?例如,如果我有两个 bin(3 到 3.5 和 3.5 到 4),我想要两个在 return 中得到两个数组,像这样 [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)
标准库中有一些 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])