3

If I have a view into part of numpy array:

import numpy as np

array = np.arange(10)
view  = array[4:8]

Can I access element to the left (in memory) of first view element, using only view identifier? enter image description here

1
  • If your array is referencing the indices of [4:8] you should be able to access it with view[0] index over the array. Commented Aug 18, 2021 at 14:18

1 Answer 1

2

view keeps a reference to array in the base attribute. view.base is array.

Thus, you could access this identifier by calling left_element = view.base[3].

If you don't know the offset of 4 that generated the view in this case, you may be able to reconstruct it by looking at raw pointers in the array interface, or simply the byte_bounds. This is easily done in this tiny example, but might be harder to get right when non-contiguous multidimensional arrays are in play, or in a different orders.

For your 1D example you could use:

offset_bytes = np.byte_bounds(view)[0] - np.byte_bounds(view.base)[0]
offset = offset_bytes // view.strides[0]
left_element = view.base[offset - 1]
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.