处理两个不同长度的数组Numpy Python



是否有一种方法可以修改下面的函数,以便它可以计算不同长度大小的数组。Numbers阵列的长度为7,Formating阵列的长度为5。下面的代码比较Formating中的任何数字是否介于两个值之间,如果是这种情况,则将两者之间的值相加。所以对于第一次计算,因为Numbers中没有元素在0, 2之间,结果将是0。代码链接源自:issue.

代码:

Numbers = np.array([3, 4, 5, 7, 8, 10,20])
Formating = np.array([0, 2 , 5, 12, 15])
x = np.sort(Numbers);
l = np.searchsorted(x, Formating, side='left')
mask=(Formating[:-1,None]<=Numbers)&(Numbers<Formating[1:,None])
N=Numbers[:,None].repeat(5,1).T
result= np.ma.masked_array(N,~mask)
result = result.filled(0)
result = np.sum(result, axis=1)

预期输出:

[ 0  7 30  0]

以下是bincounts的一种方法。注意,您把xl弄混了,我记得您可以/应该使用digitize:

# Formating goes here
x = np.sort(Formating);
# digitize
l = np.digitize(Numbers, x)
# output:
np.bincount(l, weights=Numbers)

:

array([ 0.,  0.,  7., 30.,  0., 20.])