Skip to content

Instantly share code, notes, and snippets.

@espdev
Created January 17, 2020 11:32
Show Gist options
  • Save espdev/3e517c7f5a7ba533bc1ba9b705d4c398 to your computer and use it in GitHub Desktop.
Save espdev/3e517c7f5a7ba533bc1ba9b705d4c398 to your computer and use it in GitHub Desktop.
numpy array index offset
import numpy as np
def index_offset(a):
if a.base is None:
ravel_index = 0
shape = a.shape
else:
byte_offset = np.byte_bounds(a)[0] - np.byte_bounds(a.base)[0]
ravel_index = byte_offset // a.dtype.itemsize
shape = a.base.shape
return np.unravel_index(ravel_index, shape)
if __name__ == '__main__':
a = np.ones((50, 60, 100), dtype=np.uint64)
b = a[21:46, 33:61, 78:98]
index_offset(a)
# (0, 0, 0)
index_offset(b)
# (21, 33, 78)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment