How to extract a zero dimensional slice from a one dimensional array in numpy

Is there a way to slice a zero dimensional submatrix from a one dimensional array?

For example, if I have N-dimensional ndarray


, it arr[0]

returns (N-1) -dimensional ndarray


However, if I have a 1-dimensional ndarray


, it x[0]

does not return a 0-dimensional ndarray, but rather a numpy.int64

, (if x

contains int64


Minimal example:

def increment(zero_d_array):
    zero_d_array[...] = zero_d_array + 1

counter = numpy.array(0)  # a zero-dimensional array containing scalar 0
increment(counter)        # success; counter is now 1

counters = numpy.zeros(3, dtype=int)  # [0, 0, 0]
increment(counter[1])    # fails; counter[1] is a numpy.int64, not a 0-D array


I understand that the above will work with increment(counter[1:2])

, but only because it increment()

works with both 0-D and 1-D inputs. Not all features will be that flexible.


source to share

1 answer

Use ellipsis:

increment(counter[1, ...])




All Articles