Skip to content

Instantly share code, notes, and snippets.

@seberg
Created June 13, 2019 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seberg/b0b213523a83e42fa8ffede9cb61fea9 to your computer and use it in GitHub Desktop.
Save seberg/b0b213523a83e42fa8ffede9cb61fea9 to your computer and use it in GitHub Desktop.
Python code to preprocess non-advanced indexes.
import operator
def normalize_index(index, ndim):
"""Does basic index normalization like numpy, disregards advanced indexing.
Parameters
----------
index : tuple
Indexing tuple to normalize
ndim : int
The dimension of the object that is being indexed
Returns
-------
new_index : tuple
A new index tuple, all indexing integers are guaranteed to be
python integers.
ellipsis_info : None or int
If no ellipsis exists None, otherwise the number of slices
represented by the Ellipsis.
Notes
-----
The output of a numpy index would be an array if `ellipsis_info` is 0!
The result will be scalar when `ellipsis_info is None` and the index
contains only integers.
"""
output_index = []
has_ellipsis = False
indexed_ndim = 0
out_ndim = 0
new_index = []
for ind in index:
if ind is Ellipsis:
if has_ellipsis:
raise ValueError("an index may only have one Ellipsis")
has_ellipsis = True
elif isinstance(ind, slice):
indexed_ndim += 1
out_ndim+= 1
elif ind is None:
out_ndim += 1
else:
if isinstance(ind, (bool, np.bool_)):
# Second (np.bool_) is being deprecated for operator.index
# and could be removed above.
raise IndexError("Bools are not supported as integer indices, "
"they would be interpreted as advanced index.")
ind = operator.index(ind)
indexed_ndim += 1
new_index.append(ind) # just to not convert that integer twice.
ellipsis_ndim = operator.index(ndim) - indexed_ndim
if ellipsis_ndim < 0:
raise IndexError("too many indices for array")
if not has_ellipsis and ellipsis_ndim != 0:
new_index.append(Ellipsis)
has_ellipsis = True # implicit Ellipsis
return tuple(new_index), ellipsis_ndim if has_ellipsis else None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment