随机重新分配1到0以达到指定的比率

2024-09-28 03:22:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数组

my_array = np.array([1,0,1,0,0,1,1,0,1,0])

在这个数组中,50%的项目是1。我想有效地随机地将一些1切换到0,这样比例就达到20%。你知道吗

new_array = switch_function(my_array)
print new_array 

array([0,0,0,0,0,1,0,0,1,0]) #random switching retaining order

这看起来应该很简单,我所想的一切似乎都设计过度了。谢谢你的帮助!你知道吗


Tags: 项目newmynporderfunctionrandom数组
3条回答

IIUC,这样应该行得通:

>>> arr = np.array([0,0,0,0,0,1,1,1,1,1])
>>> want_frac = 0.2
>>> n = int(round(arr.sum() - want_frac * len(arr)))
>>> indices_to_flip = np.random.choice(arr.nonzero()[0], n, replace=False)
>>> arr[indices_to_flip] = 0
>>> arr
array([0, 0, 0, 0, 0, 0, 1, 0, 1, 0])
>>> arr.mean()
0.20000000000000001

首先我们计算出需要翻转多少个数字(尽量接近正确的值),然后随机选择n个非零索引,最后将它们设置为零。你知道吗

注意,正如JFS在注释中所指出的,您应该验证n > 0,以确保您不会意外地做出您不想做的更改。你知道吗

完成这类任务有很多方法。这里有一个简单的方法。你知道吗

# Get the array length
N = len(my_array)

# Proportion of 1's
p = np.sum(my_array) / float(N)

# Locations of 1's
idx = np.arange(0, N)[my_array == 1]

# Calculate how many idx to change
k = (p*N) - (0.2 * N)

# Sample the idx and change values to 0
my_array[np.random.choice(idx, int(k), False)] = 0

如果您不需要将现有的零保持为零,并且只希望整个数组的平均值为20%1,那么您是否可以使用“for”循环遍历数组,并为每个元素调用randint(1,5)。如果randint返回1,则将数组项设置为1,否则将其设置为0。你知道吗

但是,如果您希望保留所有原始的零,这意味着您希望将1的数量减少到现在数字的40%,因此遍历数组,如果数字是1,则调用randint(1,5),如果它返回1或2,则保留原始的1,否则将其更改为零。你知道吗

相关问题 更多 >

    热门问题