1

for example:

a = np.zeros((4, 3, 2, 1))
index = (slice(0, 2, 1), 0, ...)
# a[index].shape is (2, 2, 1)

The axis 1 (second axis) of a was collapsed. I want to define a function that returns 1 with given a and index. But there are so many possibilities of index because an index might be an int, tuple, list, slice, Ellipsis, None or a tuple of them. Is there already a function that does this in any python module? If not, what is the best approach to make it? Thanks!

BuboBubo
  • 213
  • 1
  • 2
  • 5
  • I think this question is already answered [here](https://stackoverflow.com/questions/17079279/how-is-axis-indexed-in-numpys-array.) – Karthik J Dec 11 '20 at 12:38
  • That explains the mechanism of indexing. My question is how to define a function that returns which axes will be removed after indexing. It is difficult for me because there are many forms of `index`. – BuboBubo Dec 11 '20 at 12:54
  • Why do you need such a function? – hpaulj Dec 11 '20 at 15:45
  • As you say there are many possibilities, but the details are buried in the compiled `numpy` code. At some level there must be a function that calculates the return shape from the indices, and uses that to create an array to be filled with values. But that code is not available to you at the Python level. You'd have to dig into the code, or the `numpy C-API` docs. – hpaulj Dec 11 '20 at 18:05
  • I will take a look on the numpy C code. What I am doing is to make a subtype of Numpy ndarray which has 3 or 4 dimensions. I hope its `__getitem__()` returns an instance of the subtype if the first 3 axes are kept (no matter what happens to the 4th), and in other cases returns a normal `ndarray`. – BuboBubo Dec 12 '20 at 07:00

0 Answers0