這是一個函式的簡單實作,如果 x、y 或 z 中的任何一個不是 one_per_n 的倍數,則該函式將索引為 x、y、z 的 numpy 陣列的每個值設定為零:
import numpy as np
X = np.random.rand(10,10,10)
one_per_n = 4
for x in range(X.shape[0]):
for y in range(X.shape[1]):
for z in range(X.shape[2]):
if x % one_per_n != 0 or y % one_per_n != 0 or z % one_per_n != 0:
X[x,y,z] = 0
我正在尋找一種更有效的方法。
uj5u.com熱心網友回復:
在每個維度中,保留其值的元素是模數為零的元素。它們是one_per_n分開的,因此使用具有one_per_nas 步長的切片很有用。
您可以構造一個元素掩碼,為每個維度設定為 0,然后在所有這些位置將 X 歸零。
的倒數
# elements to set to zero
(x % one_per_n != 0) or (y % one_per_n != 0) or (z % one_per_n != 0)
是
# elements to keep
(x % one_per_n == 0) and (y % one_per_n == 0) and (z % one_per_n == 0)
由于反向選擇掩碼是通過邏輯與連接的,因此可以同時對它們進行切片:
# init with zeroing out everything
zero_out_mask = np.ones_like(X, dtype=bool)
# except for the modulo == 0 elements
zero_out_mask[::one_per_n, ::one_per_n, ::one_per_n] = False
X[zero_out_mask] = 0
uj5u.com熱心網友回復:
代碼的一個相當字面的 numpy 矢量化將是:
x, y, z = np.indices(X.shape, sparse=True)
X[(x % one_per_n != 0) | (y % one_per_n != 0) | (z % one_per_n != 0)] = 0
這仍然相當有效,因為模數僅針對一維陣列計算,這要歸功于sparse=True.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/521120.html
標籤:Python麻木的
上一篇:熊貓資料框不創建新列
