0

Say you have a 2D numpy array, which you have sliced in order to extract its core, just as if you were cutting out the inner frame from a larger frame.

The larger frame:

In[0]: import numpy
In[1]: a=numpy.array([[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14],[15,16,17,18,19]])
In[2]: a
Out[2]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]]) 

The inner frame:

In[3]: b=a[1:-1,1:-1]
Out[3]: 
array([[ 6,  7,  8],
       [11, 12, 13]])

My question: if I want to retrieve the position of each value in b in the original array a, is there an approach better than this?

c=numpy.ravel(a) #This will flatten my values in a, so to have a sequential order
d=numpy.ravel(b) #Each element in b will tell me what its corresponding position in a was
4
  • 2
    I'm not sure I understand what you want your program to do. What do you want to have as output? Your listing at the end of your question does not really compute the positions of b's elements in a, or does it and I'm just not able to see it? Commented Feb 2, 2017 at 14:50
  • My output is a 1D array or list containing the positions of values in the innerframe of a. Commented Feb 2, 2017 at 14:59
  • What you get is the elements of a and b as flattened arrays. So how is that the positions? They might be something like the positions in the flattened array but only because your elements are the numbers 0-19. For my understanding, a position would be something like [1, 1] for the element 6 and not the number 6 itself. Can you elaborate what you consider a "position" of the element? Commented Feb 2, 2017 at 15:05
  • I am ok if the position refers to numpy.ravel(a) instead of a directly. Commented Feb 2, 2017 at 15:09

1 Answer 1

1
y, x = np.ogrid[1:m-1, 1:n-1]
np.ravel_multi_index((y, x), (m, n))
Sign up to request clarification or add additional context in comments.

Comments

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.