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 int64
s).
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.
Use an ellipsis:
increment(counter[1, ...])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With