【发布时间】:2015-12-07 12:33:43
【问题描述】:
我正在 python 中创建一个函数,以根据 x 数组将两个数组 x 和 y 分成预定数量的 bin。我已经制作了一种有效的算法,但它真的很慢。这是(显然)有效的代码:
def sepbin(x, y, classes_number=100, log_scale=True):
if log_scale:
if x[0]<=0:
print 'Warning: zero value in array about to be log-scaled. Ignoring it.'
x=x[1:]
y=y[1:]
bins=np.logspace(np.log(x[0]), np.log(x[-1]), classes_number+1, base=np.e)
else:
bins=np.linspace(x[0], x[-1], classes_number+1)
ybins=[[] for i in range(classes_number)]
xbins=[[] for i in range(classes_number)]
for xx, yy in zip(x,y):
i=0
while i<classes_number:
if ((xx>=bins[i]) and (xx<bins[i+1])):
ybins[i].append(yy)
xbins[i].append(xx)
break
elif (i==(classes_number-1)) and xx==bins[-1]:
ybins[i].append(yy)
xbins[i].append(xx)
break
else:
i+=1
xsm = np.array(map(np.mean, xbins))
ysm = np.array(map(np.mean, ybins))
return xsm, ysm
如您所见,我想为对数缩放和线性缩放的输出腾出空间,所以我不能假设线性间隔的 bin。我只是假设数据是按新月或降序组织的(但这很容易概括)。
显然,该代码运行良好,但由于我希望使用非常大的数据集(100000 多个元素),我认为应该对其进行优化。有什么方法可以使用numpy 或scipyhere 以使其更快?我在numpy! 中找不到分箱功能,这让我有点吃惊,所以也许我看起来不太对。
谢谢。
【问题讨论】:
-
截至 2016 年,numpy 引入了
numpy.digitize()来获取索引。如果我有时间,将发布解决方案。 :)
标签: python arrays algorithm sorting