gpt4 book ai didi

python - 如何在 numpy 数组中按行随机分配值

转载 作者:太空宇宙 更新时间:2023-11-03 10:57:33 24 4
gpt4 key购买 nike

我的 google-fu 失败了!我有一个初始化为 0 的 10x10 numpy 数组,如下所示:

arr2d = np.zeros((10,10))

对于 arr2d 中的每一行,我想将 3 个随机列分配给 1。我可以使用如下循环来完成此操作:

for row in arr2d:
rand_cols = np.random.randint(0,9,3)
row[rand_cols] = 1

输出:

array([[ 0.,  0.,  0.,  0.,  0.,  0.,  1.,  1.,  1.,  0.],
[ 0., 0., 0., 0., 1., 0., 0., 0., 1., 0.],
[ 0., 0., 1., 0., 1., 1., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 1., 1., 1., 0., 0., 0.],
[ 1., 0., 0., 1., 1., 0., 0., 0., 0., 0.],
[ 1., 0., 1., 1., 0., 0., 0., 0., 0., 0.],
[ 0., 1., 0., 0., 0., 0., 1., 0., 1., 0.],
[ 0., 0., 1., 0., 1., 0., 0., 0., 1., 0.],
[ 1., 0., 0., 0., 0., 0., 1., 1., 0., 0.],
[ 0., 1., 0., 0., 1., 0., 0., 1., 0., 0.]])

有没有办法利用 numpy 或数组索引/切片以更 pythonic/优雅的方式(最好是在 1 或 2 行代码中)实现相同的结果?

最佳答案

一旦您使用 arr2d = np.zeros((10,10)) 初始化了 arr2d,您就可以使用带有 two- liner 像这样 -

# Generate random unique 3 column indices for 10 rows
idx = np.random.rand(10,10).argsort(1)[:,:3]

# Assign them into initialized array
arr2d[np.arange(10)[:,None],idx] = 1

或者如果你喜欢那样的话,把所有的东西都塞进一条线里——

arr2d[np.arange(10)[:,None],np.random.rand(10,10).argsort(1)[:,:3]] = 1

sample 运行-

In [11]: arr2d = np.zeros((10,10))  # Initialize array

In [12]: idx = np.random.rand(10,10).argsort(1)[:,:3]

In [13]: arr2d[np.arange(10)[:,None],idx] = 1

In [14]: arr2d # Verify by manual inspection
Out[14]:
array([[ 0., 1., 0., 1., 0., 0., 0., 0., 1., 0.],
[ 0., 0., 0., 0., 1., 1., 0., 0., 1., 0.],
[ 0., 0., 0., 0., 0., 1., 0., 1., 0., 1.],
[ 0., 1., 1., 0., 0., 0., 0., 0., 1., 0.],
[ 0., 0., 1., 1., 0., 0., 0., 1., 0., 0.],
[ 1., 0., 0., 0., 0., 1., 0., 0., 1., 0.],
[ 0., 0., 0., 1., 0., 0., 0., 1., 0., 1.],
[ 1., 0., 0., 0., 0., 0., 1., 0., 1., 0.],
[ 1., 0., 0., 1., 0., 0., 0., 0., 1., 0.],
[ 0., 1., 0., 1., 0., 0., 0., 0., 0., 1.]])

In [15]: arr2d.sum(1) # Verify by counting ones in each row
Out[15]: array([ 3., 3., 3., 3., 3., 3., 3., 3., 3., 3.])

注意:如果您正在寻找性能,我建议您使用 this other post 中列出的基于 np.argpartition 的方法。 .

关于python - 如何在 numpy 数组中按行随机分配值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39049716/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com