我有一个2-D numpy-array,将其解释为网格,并希望置换元素的子集。 更准确地说,边缘应映射到边缘,角落映射到角落。
np.random.shuffle完成工作,当任何元素的排列都很好。我可以通过以下方式访问角落:
a = np.arange(16).reshape((4,4)) a[[0,0,-1,-1],[0,-1,0,-1]]但是,当我打电话的时候
np.random.shuffle(a[[0,0,-1,-1],[0,-1,0,-1]])数组没有改变。 阅读https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html ,我发现上面使用的是Advanced Slicing ,它返回一个副本,而不是一个视图。 但是这个副本就地进行了混洗,因此没有结果分配给原始数组。
所以问题是,我如何置换所选指数的元素?
I have a 2-D numpy-array, interpreting it as a grid, and want to permute a subset of the elements. More precisely, an edge shall be mapped to an edge and a corner mapped to a corner.
np.random.shuffle does the job, when any permutation of elements is fine.I can access the corners by:
a = np.arange(16).reshape((4,4)) a[[0,0,-1,-1],[0,-1,0,-1]]However, when I call
np.random.shuffle(a[[0,0,-1,-1],[0,-1,0,-1]])the array is not changed. Reading https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html, I found out that the above used Advanced Slicing, which returns a copy, instead of a view. But this copy is shuffled in-place, so there is no result to be assigned to the original array.
So the questions is, how can I permute the elements of the chosen indices?
最满意答案
您可以使用np.random.permutation获取输入序列的np.random.permutation副本,然后使用索引进行分配:
In [19]: a = np.arange(16).reshape((4,4)) In [20]: a Out[20]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) In [21]: a[[0,0,-1,-1],[0,-1,0,-1]] = np.random.permutation(a[[0,0,-1,-1],[0,-1,0,-1]]) In [22]: a Out[22]: array([[12, 1, 2, 15], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [ 0, 13, 14, 3]])此外,您可以使用a[::a.shape[0]-1, ::a.shape[1]-1]查看数组的4个角
但是,由于其结果是二维numpy数组,因此改组只会沿第一轴进行混洗。
You can use np.random.permutation to get a shuffled copy of an input sequence, and then assign this using indexing:
In [19]: a = np.arange(16).reshape((4,4)) In [20]: a Out[20]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) In [21]: a[[0,0,-1,-1],[0,-1,0,-1]] = np.random.permutation(a[[0,0,-1,-1],[0,-1,0,-1]]) In [22]: a Out[22]: array([[12, 1, 2, 15], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [ 0, 13, 14, 3]])Also, you can get a view of the 4 corners of your array using a[::a.shape[0]-1, ::a.shape[1]-1]
However, since the result from that is a two-dimensional numpy array, shuffling will only shuffle along the first axis.
更多推荐
发布评论