In Python, the indexing operation for a type is implemented by the __getitem__/__setitem__/__delitem__ magic methods. To understand how indexing syntax is interpreted, and thus how these methods are called, we can simply define our own class:
class test:
def __getitem__(self, idx):
return idx
test()[:, [1,2,3], ...]
# result: (slice(None, None, None), [1, 2, 3], Ellipsis)
This slice type is a built-in type mentioned earlier in the same documentation, with a link to more specific information.
Ellipsis is simply the name of the object created by the literal syntax .... It's what Numpy uses to represent the complete extent of any number of axes - so this lets us avoid worrying about the dimensionality of the array we're working with.
The important thing to realize is that we can use that same index tuple directly, to get the same result.
Thus, given a dimension along which to slice with [ci], we can construct the necessary tuple, and index with it:
all = slice(None)
def make_index(ci, dimension):
return (all,) * dimension + ([ci], Ellipsis)
# Now we can do things like:
arr[make_index(ci, dimension)] = some_data
Answer from Karl Knechtel on Stack OverflowI'm making a program that does some processing for material dispersal in bomb explosions, working on numpy arrays to be converted into geo raster files and eventually displayed in ArcGIS.
It was my understanding that a slice of a numpy array is a view, and so altering the data on it should alter it on the original array. But I keep returning arrays with all zero values. If this is not the case, I can't seem to find any easy way to apply a function to just a part of a multidimensional array.
Here is the part of the code in question.