簡體   English   中英

使用 2 個不同長度的 arrays Numpy Python

[英]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的方法。 請注意,您的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.])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM