Numpy元组的随机选择 [英] Numpy random choice of tuples

查看:230
本文介绍了Numpy元组的随机选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在创建一个随机选择数组时遇到了麻烦,其中一个选择是一个元组.

I'm having trouble to create an array of random choices, where a choice is a tuple.

我收到错误:a must be 1-dimensional

这里是一个例子:

choices = ((0,0,0),(255,255,255))
numpy.random.choice(choices,4)

还有其他方法吗?

预期结果:

从选择元组中随机选择的由4个元素组成的numpy数组.

a numpy array consiting of 4 elements randomly picked from the choices tuple.

((0,0,0),(0,0,0),(255,255,255),(255,255,255))

推荐答案

使用choice选择1dim indices 到数组中,然后对其进行索引.

Use choice to choose the 1dim indices into the array, then index it.

在您提供的示例中,仅数字个可能的选择会影响选择的性质,而不影响实际值(0、255).选择索引是1dim问题,choice知道如何处理.

In the example you provided, only the number of possible choices affects the nature of the choice, not the actual values (0, 255). Choosing indices is the 1dim problem choice knows how to handle.

choices = numpy.array([[0,0,0],[255,255,255]])
idx = numpy.random.choice(len(choices),4)
choices[idx]

这篇关于Numpy元组的随机选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆