从NumPy阵列中随机选择细胞-无需替换 [英] Select cells randomly from NumPy array - without replacement

查看:80
本文介绍了从NumPy阵列中随机选择细胞-无需替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在NumPy中编写一些建模例程,这些例程需要从NumPy数组中随机选择单元并对其进行一些处理.必须选择所有单元格而不替换它们(例如,一旦选择了一个单元格,就不能再次选择它,但是必须在最后选择所有单元格.)

I'm writing some modelling routines in NumPy that need to select cells randomly from a NumPy array and do some processing on them. All cells must be selected without replacement (as in, once a cell has been selected it can't be selected again, but all cells must be selected by the end).

我正在从IDL过渡,在那里我可以找到一种很好的方法来完成此操作,但是我认为NumPy也有一种很好的方法来执行此操作.您会提出什么建议?

I'm transitioning from IDL where I can find a nice way to do this, but I assume that NumPy has a nice way to do this too. What would you suggest?

更新:我应该说过我正在尝试在2D数组上执行此操作,因此会获得一组2D索引.

Update: I should have stated that I'm trying to do this on 2D arrays, and therefore get a set of 2D indices back.

推荐答案

如果仍然需要原始数组,如何使用numpy.random.shufflenumpy.random.permutation?

How about using numpy.random.shuffle or numpy.random.permutation if you still need the original array?

如果需要就地更改数组,则可以像这样创建索引数组:

If you need to change the array in-place than you can create an index array like this:

your_array = <some numpy array>
index_array = numpy.arange(your_array.size)
numpy.random.shuffle(index_array)

print your_array[index_array[:10]]

这篇关于从NumPy阵列中随机选择细胞-无需替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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