我想知道用給定條件的數組中其他隨機元素替換數組中元素的最有效方法。更具體地說,我需要將不符合給定條件的每個元素替換爲該行中的另一個隨機值。例如,我想將每行數據替換爲介於-.8和.8之間的數據(行)中的隨機單元格。我inefficinet解決方案看起來是這樣的:Python中的高效數組替換
import numpy as np
data = np.random.normal(0, 1, (10, 100))
for index, row in enumerate(data):
row_copy = np.copy(row)
outliers = np.logical_or(row>.8, row<-.8)
for prob in np.where(outliers==1)[0]:
fixed = 0
while fixed == 0:
random_other_value = r.randint(0,99)
if random_other_value in np.where(outliers==1)[0]:
fixed = 0
else:
row_copy[prob] = row[random_other_value]
fixed = 1
顯然,這是沒有效率的。
我真的很感激這個答案。如果你有一點時間,你能否更多地解釋一下這條線是幹什麼的? row_copy = np.array([if if else] f,x iniziz(good_ones,row)]]) – mike
當然。我會把答案放在答案中。往上看。 – steveha