4

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.

SuperElectric
  • 17,548
  • 10
  • 52
  • 69
  • I'm not sure there is a way. Zero-d arrays are a bit of an oddity in Numpy. Is there a reason you actually need to do this? – BrenBarn Oct 10 '14 at 17:42
  • I often find zero-d arrays to be a useful way of having "boxed" primitives, like an int I can pass to a function to have it modified in-place (something you can't do with plain ints). As I mention in the question, obviously there are workarounds like using size-1 1-D slices instead, but these are more verbose. – SuperElectric Oct 10 '14 at 17:48
  • Yeah, but the question is do you need to be able to get them by slicing? If you just want to keep a zero-d counter around, you can do it as you showed by creating it explicitly. So what I mean is, what are you actually doing that makes you want to generically slice and increment arrays of any dimension, instead of just making your counter and incrementing it? – BrenBarn Oct 10 '14 at 17:51

1 Answers1

7

Use an ellipsis:

increment(counter[1, ...])
ecatmur
  • 152,476
  • 27
  • 293
  • 366