【发布时间】: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 变量做一些事情,但我不确定如何根据截止值拆分数据。感谢您的帮助。
使用代码:
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