我正在使用np.digitize将Python中的2d数组(x by y)合并到其x值的区间(在“bins”中给出):
elements_to_bins = digitize(vals,bins)
其中“vals”是一个二维数组,即:
vals = array([[1,v1],[2,v2],...]).
elements_to_bins只是说每个元素落入哪个bin.我当时想要做的是得到一个列表,其长度是“箱子”中的箱数,每个元素返回落入该箱的“val”的y维度.我现在这样做:
points_by_bins = []
for curr_bin in range(min(elements_to_bins),max(elements_to_bins) + 1):
curr_indx = where(elements_to_bins == curr_bin)[0]
curr_bin_vals = vals[:,curr_indx]
points_by_bins.append(curr_bin_vals)
有没有更优雅/更简单的方法来做到这一点?我只需要列出每个bin中的y值列表.
谢谢.
最佳答案
如果我理解你的问题:
原文链接:https://www.f2er.com/python/439029.htmlvals = array([[1,10],[1,11],20],21],22]]) # Example
(x,y) = vals.T # Shortcut
bin_limits = range(min(x)+1,max(x)+2) # Other limits could be chosen
points_by_bin = [ [] for _ in bin_limits ] # Final result
for (bin_num,y_value) in zip(searchsorted(bin_limits,x,"right"),y): # digitize() finds the correct bin number
points_by_bin[bin_num].append(y_value)
print points_by_bin # [[10,[20,21,22]]
Numpy的快速数组操作searchsorted()用于最大效率.然后逐个添加值(因为最终结果不是矩形数组,Numpy对此无能为力).此解决方案应该比循环中的多个where()调用更快,这会迫使Numpy多次重新读取同一个数组.