Index the middle of a numpy array?

Late, but for everyone else running into this issue: A much smoother way is to use numpy's take or put.

To address the middle of an array you can use put to index an n-dimensional array with a single index. Same for getting values from an array with take

Assuming your array has an odd number of elements, the middle of the array will be at half of it's size. By using an integer division (// instead of /) you won't get any problems here.

import numpy as np

arr = np.array([[0, 1, 2],
                [3, 4, 5],
                [6, 7, 8]])

# put a value to the center 
np.put(arr, arr.size // 2, 999)
print(arr)

# take a value from the center
center = np.take(arr, arr.size // 2)
print(center)


as cge said, the simplest way is by turning it into a lambda function, like so:

x = np.arange(10)
middle = lambda x: x[len(x)/4:len(x)*3/4]

or the n-dimensional way is:

middle = lambda x: x[[slice(np.floor(d/4.),np.ceil(3*d/4.)) for d in x.shape]]

Tags:

Python

Numpy