【问题标题】:Numpy: Replace 500 random elements in an array from 0 to 1Numpy:将数组中的 500 个随机元素从 0 替换为 1
【发布时间】:2022-11-13 07:46:24
【问题描述】:

Numpy:将数组中的 500 个随机元素从 0 替换为 1

import numpy as np
import random

# 2D Grid world of 100 x 100 cells
arr = np.zeros((100,100))

# Arbitrarily change 500 elements from 0 to 1 
for 

【问题讨论】:

  • 我想创建一个 1000 x 1000 单元格的 2D 网格世界,并任意选择 500 个单元格来表示障碍物

标签: arrays numpy loops random np


【解决方案1】:

您可以选择 0 到 100*100 之间的 500 个随机唯一数字来将您的数组索引为 1D 并分配 1:

import numpy as np

# 2D Grid world of 100 x 100 cells
arr = np.zeros((100,100))

arr.flat[np.random.choice(np.arange(arr.size), 500, replace=False)] = 1

10x10 数组中有 10 个随机 1 的示例:

arr = np.zeros((10,10), dtype=int)

arr.flat[np.random.choice(np.arange(arr.size), 10, replace=False)] = 1

print(arr)

输出:

[[0 0 0 0 0 0 0 0 1 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 1]
 [0 1 0 0 0 0 0 0 0 1]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [1 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 1 0 0 1]
 [1 1 0 0 1 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]]

【讨论】:

    猜你喜欢
    • 2015-10-02
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多