我想知道用给定条件的数组中其他随机元素替换数组中元素的最有效方法。更具体地说,我需要将不符合给定条件的每个元素替换为该行中的另一个随机值。例如,我想将每行数据替换为介于-.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