从列表中创建一个均匀采样值的numpy数组

时间:2019-02-25 14:44:52

标签: python python-3.x numpy

说我有一个值列表,例如:[9,17,2]

创建n维numpy数组(例如[110 x 90 x 11]说)的最佳方法是什么,该数组由列表中的值随机填充,但要均匀采样?

2 个答案:

答案 0 :(得分:0)

)您可以使用random.randrange随机选择数字

import random
import numpy as np

l=[9, 17, 2]
arrayshape=[110,90,11]

#random.randrange(len(l)) generates random indexes
#l[random.randrange(len(l))] select random indexes from list
#for i in range(110*90*11) how many number we need
#np.array(...) make an array from list
#np.reshape(... ,arrayshape) reshaping array to our shape
array=np.reshape(np.array([l[random.randrange(len(l))] for i in range(110*90*11)]),arrayshape)

答案 1 :(得分:0)

使用

np.random.choice(arr, (9, 17, 2))

random.choice默认情况下将从arr中以均匀的概率和替换(并具有给定的形状)随机抽取一个样本。