简体   繁体   English

用不同范围内的随机数填充 1D numpy 可变长度数组的有效方法

[英]Efficient way to fill a 1D numpy array of variable length with random numbers in different ranges

I need to fill a length n 1D numpy array with random numbers from the ranges [1,2,...,n], [2,3,...,n], [3,4,...,n], ..., [n-1,n] and [n] respectively.我需要用 [1,2,...,n]、[2,3,...,n]、[3,4,...,n 范围内的随机数填充长度为 n 1D numpy 的数组], ..., [n-1,n] 和 [n] 分别。 I am looking for a vectorize solution to this problem.我正在寻找这个问题的矢量化解决方案。 Thanks very much in advance.首先十分感谢。

You could use numpy.random.randint, for this:为此,您可以使用 numpy.random.randint:

import numpy as np

n = 10
res = np.random.randint(np.arange(0, n), n)
print(res)

Output Output

[3 3 2 6 6 7 6 8 9 9]

From the documentation :文档中:

Generate a 1 by 3 array with 3 different lower bounds生成具有 3 个不同下限的 1 x 3 数组

np.random.randint([1, 5, 7], 10) array([9, 8, 7]) # random

The more up-to-date alternative is to use integers :更新的替代方法是使用整数

import numpy as np

n = 10
rng = np.random.default_rng()
res = rng.integers(np.arange(0, n), n)

print(res)

Note: The examples above start from 0 , choose the intervals that suit best your problem.注意:以上示例从0开始,选择最适合您问题的间隔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM