我想為i陣列X(即Boolean)所在的每個索引創建一個回圈True。
是不是有什么更有效的/比Python的包裝np.nonzero里面np.nditer如下?
for i in np.nditer(np.nonzero(X), flags=['zerosize_ok']):
myfunction(Y[i],Z2[Z[i]])
這里的問題是它迭代兩次而不是一次,并且占用記憶體(首先,np.nonzero迭代X并將其存盤到一個大陣列,然后np.nditer迭代該陣列)。
是否有一個命令(可以np.nditer這么說,有點類似于)用于直接有效地迭代True布爾陣列的條目,而不用np.nonzero首先明確列出它們?(迭代所有條目并使用if陳述句檢查每個條目的效率可能低于 Numpy 提供的某些迭代器(如果存在)。
uj5u.com熱心網友回復:
人們反對是因為回圈遍歷 numpy 陣列的條目是一個很大的問題。我們使用 numpy 是因為它速度快,并且單獨處理每個元素而不是一次對整個陣列進行操作,因此您可以獲得 python 級別的性能而不是 numpy/c 性能。
希望通過提供具有真值和假值的陣列來排除值是很常見的,稱為掩碼。你可以通過索引到真偽陣列來做到這一點。要在 numpy 中做到這一點,您可以使用索引。例如你做 np.array([1,2,3])[np.array([True,False,True])]。它給你np.array([1, 3])。
所以基本上嘗試以你可以做的方式安排事情
myfunction(Y[mask],Z2[Z[maks]]).
有幾種方法可以做到這一點。一種方法是僅使用 numpy 函式來創建 myfunction,另一種方法是使用裝飾器,例如numba.vectorize, numba.guvectorizeornumba.njit等等。
uj5u.com熱心網友回復:
如何將numpy.vectorise與布爾選擇器一起用作索引?
np.vectorise 接受一個函式并回傳該函式的向量化版本,它接受陣列。然后,您可以使用選擇器在陣列或其子集上運行該函式。
在 numpy 中,您可以使用數字串列使用陣列的索引進行子選擇。
所述numpy.where函式回傳匹配的某個值或函式陣列的索引。
把它放在一起:
import numpy as np
import random
random.seed(0) # For repeatability
def myfunction(y, z, z2):
return y*z2[z]
Y = np.array(range(100)) # Array of any length
Z = np.array(range(len(Y))) # Must be the same length as Y
Z2 = np.array(range(len(Y))) # Must be constrained to indexes of X, Y and Z
X = [random.choice([True, False]) for toss in range(len(Y))] # Throw some coins
# X is now an array of True/False
# print( "\n".join(f"{n}: {v}" for n, v in enumerate(X)))
print(np.where(X)) # Where gets the indexes of True items
# Vectorise our function
vfunc = np.vectorize(myfunction, excluded={2}) # We exclude {2} as it's the Z2 array
# Do the work
res = vfunc(Y[np.where(X)],Z[np.where(X)],Z2)
# Check our work
for outpos, inpos in enumerate(np.where(X)[0]):
assert myfunction(Y[inpos], Z[inpos], Z2) == res[outpos], f"Mismatch at in={inpos}, out={outpos}"
# Print the results
print(res)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/392562.html
