conquistador
conquistador

Reputation: 693

Getting an item's neighbor inside of a numpy array

I have an array that looks like this:

[['A0' 'B0' 'C0']
 ['A1' 'B1' 'C1']
 ['A2' 'B2' 'C2']]

I would like to get B1's neighbors which are B0 , C1 , B2 , A1, along with their indices.

This is what I came up with:

import numpy as np


arr = np.array([
    ['A0','B0','C0'],
    ['A1','B1','C1'],
    ['A2','B2','C2'],
])


def get_neighbor_indices(x,y):
    neighbors = []
    try:
        top = arr[y - 1, x]
        neighbors.append((top, (y - 1, x)))
    except IndexError:
        pass
    try:
        bottom = arr[y + 1, x]
        neighbors.append((bottom, (y + 1, x)))
    except IndexError:
        pass
    try:
        left = arr[y, x - 1]
        neighbors.append((left, (y, x - 1)))
    except IndexError:
        pass
    try:
        right = arr[y, x + 1]
        neighbors.append((right, (y, x + 1)))
    except IndexError:
        pass
    return neighbors

This will return a list of tuples (value, (y, x)).

Is there a better way to do this without relying on try/except?

Upvotes: 3

Views: 397

Answers (3)

Mad Physicist
Mad Physicist

Reputation: 114230

You can do this directly in numpy without any exceptions, since you know the sizes of your array. The indices of the immediate neighbors of x, y are given by

inds = np.array([[x, y]]) + np.array([[1, 0], [-1, 0], [0, 1], [0, -1]])

You can easily make a mask that indicates which indices are valid:

valid = (inds[:, 0] >= 0) & (inds[:, 0] < arr.shape[0]) & \
        (inds[:, 1] >= 0) & (inds[:, 1] < arr.shape[1])

Now extract the values that you want:

inds = inds[valid, :]
vals = arr[inds[:, 0], inds[:, 1]]

The simplest return value would be inds, vals, but if you insisted on keeping your original format, you could transform it into

[v, tuple(i) for v, i in zip(vals, inds)]

Addendum

You can easily modify this to work on arbitrary dimensions:

def neighbors(arr, *pos):
    pos = np.array(pos).reshape(1, -1)
    offset = np.zeros((2 * pos.size, pos.size), dtype=np.int)
    offset[np.arange(0, offset.shape[0], 2), np.arange(offset.shape[1])] = 1
    offset[np.arange(1, offset.shape[0], 2), np.arange(offset.shape[1])] = -1
    inds = pos + offset
    valid = np.all(inds >= 0, axis=1) & np.all(inds < arr.shape, axis=1)
    inds = inds[valid, :]
    vals = arr[tuple(inds.T)]
    return vals, inds

Given an N dimensional array arr and N elements of pos, you can create the offsets by just setting each dimension sequentially to 1 or -1. The computation of the mask valid is greatly simplified by broadcasting together inds and arr.shape, as well as calling np.all across each N-sized row instead of doing it manually for each dimension. Finally, the conversion tuple(inds.T) turns inds into an actual fancy index by assigning each column to a separate dimension. The transpose is necessary becaue arrays iterate over rows (dim 0).

Upvotes: 5

Aryerez
Aryerez

Reputation: 3495

You can use this:

def get_neighbours(inds):
    places = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    return [(arr[x, y], (y, x)) for x, y in [(inds[0] + p[0], inds[1] + p[1]) for p in places] if x >= 0 and y >= 0]

get_neighbours(1, 1)
# OUTPUT [('B0', (1, 0)), ('B2', (1, 2)), ('A1', (0, 1)), ('C1', (2, 1))]

get_neighbours(0, 0)
# OUTPUT [('A1', (0, 1)), ('B0', (1, 0))]

Upvotes: 1

Andrew Kay
Andrew Kay

Reputation: 274

How about this?

def get_neighbor_indices(x,y):
    return ( [(arr[y-1,x], (y-1, x))] if y>0 else [] ) + \
           ( [(arr[y+1,x], (y+1, x))] if y<arr.shape[0]-1 else [] ) + \
           ( [(arr[y,x-1], (y, x-1))] if x>0 else [] ) + \
           ( [(arr[y,x+1], (y, x+1))] if x<arr.shape[1]-1 else [] )

Upvotes: 0

Related Questions