我有兩個 1D NumPy 陣列 x = [x[0], x[1], ..., x[n-1]] 和 y = [y[0], y[1], ..., y[ n-1]]。陣列 x 是已知的,我需要確定陣列 y 的值。對于 np.arange(n) 中的每個索引,y[index] 的值取決于 x[index] 和 x[index 1: ]。我的代碼是這樣的:
import numpy as np
n = 5
q = 0.5
x = np.array([1, 2, 0, 1, 0])
y = np.empty(n, dtype=int)
for index in np.arange(n):
if (x[index] != 0) and (np.any(x[index 1:] == 0)):
y[index] = np.random.choice([0,1], 1, p=(1-q, q))
else:
y[index] = 0
print(y)
for 回圈的問題是在我的實驗中 n 的大小會變得非常大。有沒有矢量化的方法來做到這一點?
uj5u.com熱心網友回復:
y隨機生成具有完整形狀的陣列。- 生成一個 bool 陣列,指示在何處設定零。
- 用于
np.where設定零。
嘗試這個,
import numpy as np
n = 5
q = 0.5
x = np.array([1, 2, 0, 1, 0])
y = np.random.choice([0, 1], n, p=(1-q, q))
condition = (x != 0) & (x[::-1].cumprod() == 0)[::-1] # equivalent to the posted one
y = np.where(condition, y, 0)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/533776.html
標籤:Python数组麻木的
