[英]Working with 2 arrays with different lengths Numpy Python
有沒有辦法可以修改下面的 function 以便它可以計算不同長度大小的 arrays。 Numbers
數組的長度為 7,Formatting 的長度為 5。下面的代碼比較了Formating
中的任何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)
預期 output:
[ 0 7 30 0]
這是一種使用bincounts
的方法。 請注意,您的x
和l
搞砸了,我記得您可以/應該使用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.])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.