Get value out of numpy array view boundaries

Viewed 117

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 Answers

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