Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to extract a zero-dimensional slice from a 1-dimensional array in numpy

Is there a way to slice a zero-dimensional sub-array from a 1-dimensional array?

For example, if I have a N-dimensional ndarray arr, arr[0] returns a (N-1)-dimensional ndarray.

However, if I have a 1-dimensional ndarray x, x[0] doesn't return a 0-dimensional ndarray, but rather a numpy.int64, (if x contains int64s).

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 realize the above would work with increment(counter[1:2]), but only because increment() happens to work with both 0-D and 1-D inputs. Not all functions will be so flexible.

like image 891
SuperElectric Avatar asked Mar 19 '23 06:03

SuperElectric


1 Answers

Use an ellipsis:

increment(counter[1, ...])
like image 103
ecatmur Avatar answered Mar 26 '23 03:03

ecatmur