Python Numpy Array geht values of neighbours
I want to get all neighbour values of a np.array.
The array looks like:
x = np.array([ [1, 2, 3, 4 ], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ])
What I have is:
i = 2 j = 2 n = x[i,j-1], x[i,j], x[i,j+1], x[i-1,j], x[i+1,j], x[i-1,j-1], x[i+1,j+1], x[i+1,j-1], x[i-1,j+1]
This returns (what I want)
(10, 11, 12, 7, 15, 6, 16, 14, 8)
But also got bugs for example when i want the neightbour values of
i = 3 j = 3
Exception has occurred: IndexError index 4 is out of bounds for axis 1 with size 4
An other soultion is:
def find_neighbors(m, i, j, dist=1): return [row[max(0, j-dist):j+dist+1] for row in m[max(0,-1):i+dist+1]]
n = find_neighbors(x, i, j)
Which gives me an array of the neightbours but also gives me not all neightbours when I set
i = 0 j = 0
because it only gives me:
[array([1, 2]), array([5, 6])]
Does anybody have a solution for this?
You can take advantage of python indexing wrapping around for negative indices.
def wrap_nb(x,i,j): return x[np.ix_(*((z-1, z, z+1-S) for z,S in zip((i,j), x.shape)))].ravel()
j to be nonnegative and less than the shape of
If that is not guaranteed:
def wrap_nb(x,i,j): return x[np.ix_(*(np.r_[z-1:z+2]%S for z,S in zip((i,j), x.shape)))].ravel()
>>> wrap_nb(x,1,-2) array([ 2, 3, 4, 6, 7, 8, 10, 11, 12]) >>> wrap_nb(x,0,-1) array([15, 16, 13, 3, 4, 1, 7, 8, 5]) >>> wrap_nb(x,0,0) array([16, 13, 14, 4, 1, 2, 8, 5, 6])
Compare neighbors in array, I have a a python function for taking in a 2D numpy array and checking if each element is the same as its neighbor elements. I feel like there's a more efficient� Now the next option, and one that better suits you using numpy arrays is something called convolution. It looks complicated but basically you have a kernel that you smear across an entire array. All of its values multiply against the area of the array it is over and the sum goes in the cell (basically exactly what you want).
# function to find the start row and column def find_start(x): start = x-1 if x-1 >= 0 else 0 return start # function to find the end row and column def find_end(x, shape): end = x+1 if x+1 <= shape else shape return end def find_neighbors(a, i, j): neighbors =  row_start, row_end = find_start(i), find_end(i, a.shape) col_start, col_end = find_start(j), find_end(j, a.shape) for y in range(a.shape): for z in range(a.shape): if y >= row_start and y <= row_end: if z >= col_start and z <= col_end: neighbors.append(a[y][z]) return neighbors i, j = 0, 0 neighbors = find_neighbors(a, i, j) print(neighbors)
[1, 2, 5, 6]
i, j = 3, 3 neighbors = find_neighbors(a, i, j) neighbors
[11, 12, 15, 16]
i, j = 2, 2 neighbors = find_neighbors(a, i, j) neighbors
[6, 7, 8, 10, 11, 12, 14, 15, 16]
This would cover all the edge cases.
How to compare fast the value with the ones of neighbours in a 3D , NumPy performs operations in a vectorised manner, you should try and operate on the whole array and avoid explicit loops. e.g. np.argwhere(� If any of the neighbor values is na then skip that neighbour in getting the average. Answer: Shot #1. This assumes you are looking to get sliding windowed average values in an input array with a window of 3 x 3 and considering only the north-west-east-south neighborhood elements. For such a case, signal.convolve2d with an appropriate kernel
I got the following solution form an mate:
homes = np.array([ [1, 2, 3, 4 ], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ])
Code for returning the neighbour values:
neighbour =  neighbour += [homes[i][j]] # value itself neighbour += [homes[i][(j + 1) % n]] # value right neighbour += [homes[i][(j - 1) % n]] # value left neighbour += [homes[(i + 1) % n][j]] # value down neighbour += [homes[(i + 1) % n][(j + 1) % n]] # value right down neighbour += [homes[(i + 1) % n][(j - 1) % n]] # value left down neighbour += [homes[(i - 1) % n][j]] # vlaue up neighbour += [homes[(i - 1) % n][(j + 1) % n]] # vlaue right up neighbour += [homes[(i - 1) % n][(j - 1) % n]] # value left up
Which returns me:
i = 0 j = 0 [16, 13, 15, 4, 1, 3, 12, 9, 11]
Thats what I need but I'am still interessed in solution like the one from Abdur
Python Numpy Array geht значения соседей, Я хочу получить все соседние значения np.array. neighbour =  neighbour += [homes[i][j]] # value itself neighbour += [homes[i][(j + 1) % n]]� Data manipulation in Python is nearly synonymous with NumPy array manipulation: even newer tools like Pandas are built around the NumPy array.This section will present several examples of using NumPy array manipulation to access data and subarrays, and to split, reshape, and join the arrays.
numpy.take — NumPy v1.19 Manual, Take elements from an array along an axis. When axis is not A call such as np. take(arr, indices, axis=3) is equivalent to arr[:,:,:,indices,] . Access Array Elements. Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.
sklearn.neighbors.radius_neighbors_graph — scikit-learn 0.23.2 , scikit-learn: machine learning in Python. sklearn.neighbors. radius_neighbors_graph (X, radius, *, mode='connectivity', metric='minkowski', p= 2, metric_params=None, Sample data, in the form of a numpy array or a precomputed BallTree . Python : Find unique values in a numpy array with frequency & indices | numpy.unique() How to Reverse a 1D & 2D numpy array using np.flip() and  operator in Python; 6 Ways to check if all values in Numpy Array are zero (in both 1D & 2D arrays) - Python; How to get Numpy Array Dimensions using numpy.ndarray.shape & numpy.ndarray.size() in Python
Contents of numpy ndArray [ 1 3 5 7 9 11 13 15 17 19] *** Select an element by Index *** Element at 2nd index : 5 *** Select a by sub array by Index Range *** Sub Array from 1st to 6th index are : [ 3 5 7 9 11 13] Sub Array from beginning to 3rd index are : [1 3 5 7] Sub Array from 2nd index to end are : [ 5 7 9 11 13 15 17 19] *** Sub Array is
- You can find a solution here: stackoverflow.com/questions/22550302/find-neighbors-in-a-matrix.
- I think this solution is even more pythonic: stackoverflow.com/questions/7442570/….
- What would the desired result for
- @VasilisG Should be ``` [16, 13, 15, 4, 1, 3, 12, 9, 11] ``` @dome I saw them but they didn't help
- Hey thank you for the solution! I will have a look on this when I get back home!
- I set the "a" to an "x" i your code and I can confirm you output. Thank you! But maybe I don't understand the function but I need for ` i = 0 j = 0 ` This output: ` [1, 2, 4, 5, 6, 8, 13, 14, 16] `
i = 0, j = 0is the first element and it should have only 3 neighbors. One on its right -> 2, one on its bottom -> 5 and one on its diagonal -> 6. So output will contain 4 element (3 neighbors and one itself).
- @Pablo if this solution worked, please accept the answer.
- Thats right. But I need the others for my programm too :P
- @Pablo I can understand you have requirement but to solve a problem we must have some pattern. It's ok if you want those numbers but problem for me is, on basis of what logic you derived those numbers. Because there must be some logic or pattern so we can apply that on whole array to make our results consistent. But if we talk about true neighbors, then this solution covers that. If you still want to satisfy your requirements, you can open a new question but please mention some pattern or logic to extract the result.