我有一個像這樣的 3D-np.array
s = np.array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]], dtype=float)
呼叫陣列元素的 (x, y, z) id 坐標,我如何使用 numpy 來計算s[x, y, z] /= np.sum(s[:, :, z])
ex:
x, y, z = s.shape
s1 = s.copy()
for i in range(x):
for j in range(y):
for k in range(z):
s1[i, j, k] = s[i, j, k] / np.sum(s[:, :, k])
# I use s1 cause I scare s will change after every loop
# and np.sum(s[:,:,k]) is not a const
# pseudo-code example:
# s[0, 0, 1] = 1
# sum[:, :, 1] = 117 # sum of 2nd column
# then
# s[0,0,1] = 1/117
# repeat with x*y*z-1 point remain
我曾嘗試使用,np.fromfunction但如果運行速度太慢。我的代碼例如:
def f(x, y, z):
result = s[x, y, z] / np.sum(s[:, :, z])
return result
s1 = np.fromfunction(np.vectorize(f), (a, b, c), dtype='int')
# a, b, c is shape of the array
我可以在沒有 for 回圈的情況下以更快的方式完成此操作嗎?
uj5u.com熱心網友回復:
關于什么
s/s.sum(axis=(0, 1), keepdims=True)
或等效地
s/np.sum(s, axis=(0, 1), keepdims=True)
引數axis指定sum執行的維度。keepdims允許求和的結果保持其原始維度-3在當前情況下 - 這使得除法廣播-gnostique。
uj5u.com熱心網友回復:
如果您只想將陣列的所有元素除以某個值,只需呼叫除法而不對陣列進行索引就足夠了。
test = np.array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]])
print(test/np.sum(test[:,:,1]))
或者,如果您想將其嵌入到函式中:
def array_divide(inputArr):
return inputArr/np.sum(inputArr[:,:,1])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/371778.html
