21

To index the middle points of a numpy array, you can do this:

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

Is there a shorthand for indexing the middle of the array? e.g., the n or 2n elements closes to len(x)/2? Is there a nice n-dimensional version of this?

5
  • I don't think there is a better way other than what you have created. The most similar thing in the library is probably np.fft.fftshift which shifts the array to place the middle at index 0. Commented Mar 6, 2013 at 21:07
  • Yeah, that was the other option I had considered, but it's not a ton better: you'd need to do x = np.concatenate([np.fftshift[:n],np.fftshift[-n:]]) or similar. Commented Mar 7, 2013 at 0:32
  • 1
    It seems like just making this a function (eg, mid = lambda x: x[len(x)/4:len(x)*3/4]) would be the simplest solution. Commented Mar 7, 2013 at 22:18
  • 2
    You can use slice objects for the n-dimensional case: mid = lambda x: x[[slice(np.floor(d/4.),np.ceil(3*d/4.)) for d in x.shape]] Commented Mar 28, 2013 at 2:15
  • @cge Maybe you should post that as an answer. Commented Apr 5, 2013 at 17:45

2 Answers 2

7

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)

Sign up to request clarification or add additional context in comments.

Comments

6

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]]

1 Comment

fast forward 4 years, and this now produces a warning "VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.