简体   繁体   English

索引环绕的 numpy 二维数组

[英]Indexing numpy 2D array that wraps around

How do you index a numpy array that wraps around when its out of bounds?你如何索引一个在超出边界时环绕的 numpy 数组?

For example, I have 3x3 array:例如,我有 3x3 数组:

import numpy as np

matrix = np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]])

## 
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]
 [11 12 13 14 15]]

Say I would like to index the values around index (2,4) where value 15 is located.假设我想索引值15所在的索引 (2,4) 周围的值。 I would like to get back the array with values:我想用值取回数组:

[[9,  10, 6]
 [14, 15, 11]
 [4,  5,  1]]

Basically all the values around 15 was returned, assuming it wraps around基本上所有 15 左右的值都被返回,假设它环绕

A fairly standard idiom to find the neighboring elements in a numpy array is arr[x-1:x+2, y-1:y+2] .numpy数组中查找相邻元素的一个相当标准的习惯用法是arr[x-1:x+2, y-1:y+2] However, since you want to wrap, you can pad your array using wrap mode, and offset your x and y coordinates to account for this padding.但是,由于您想要换行,您可以使用换行模式填充数组,并偏移xy坐标以考虑此填充。

This answer assumes that you want the neighbors of the first occurence of your desired element.此答案假定您想要所需元素第一次出现的邻居。


First, find the indices of your element, and offset to account for padding:首先,找到元素的索引和偏移量以考虑填充:

x, y = np.unravel_index((m==15).argmax(), m.shape)
x += 1; y += 1

Now pad , and index your array to get your neighbors:现在pad ,并索引您的数组以获取您的邻居:

t = np.pad(m, 1, mode='wrap')    
out = t[x-1:x+2, y-1:y+2]  

array([[ 9, 10,  6],
       [14, 15, 11],
       [ 4,  5,  1]]) 

Here's how you can do it without padding.这是您无需填充即可完成的操作。 This can generalize easily to when you want more than just one neighbor and without the overhead of padding the array.这可以很容易地推广到当您想要多个邻居并且没有填充数组的开销时。

def get_wrapped(matrix, i, j):
  m, n = matrix.shape
  rows = [(i-1) % m, i, (i+1) % m]
  cols = [(j-1) % n, j, (j+1) % n]
  return matrix[rows][:, cols]

res = get_wrapped(matrix, 2, 4)

Let me explain what's happening here return matrix[rows][:, cols] .让我解释一下这里发生了什么return matrix[rows][:, cols] This is really two operations.这真的是两个操作。

The first is matrix[rows] which is short hand for matrix[rows, :] which means give me the selected rows, and all columns for those rows.第一个是matrix[rows] ,它是matrix[rows, :]简写matrix[rows, :]这意味着给我选定的行,以及这些行的所有列。

Then next we do [:, cols] which means give me all the rows and the selected cols.然后接下来我们做[:, cols]这意味着给我所有的行和选定的 cols。

The take function works in-place. take函数就地工作。

>>> a = np.arange(1, 16).reshape(3,5)
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10],
       [11, 12, 13, 14, 15]])
>>> b = np.take(a, [3,4,5], axis=1, mode='wrap')
array([[ 4,  5,  1],
       [ 9, 10,  6],
       [14, 15, 11]])
>>> np.take(b, [1,2,3], mode='wrap', axis=0)
array([[ 9, 10,  6],
       [14, 15, 11],
       [ 4,  5,  1]])

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

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