0

I have a numpy array of indeterminate size and I need to compare some indices being used to extract data. For example if start_index > end_index I want an error to be thrown. However, sometimes the indices might be negative, most notably we might have end_index = -1 to represent the final element in the array. If I just straight up compared the indices and end_index was negative an error could be thrown incorrectly.

My current solution is to check if start_index % array_length > end_index % array_length.

This does work, but I'm now having to think about everything using modular arithmetic. Does anyone know of a more efficient solution, perhaps a tool from numpy itself?

LukeC92
  • 121
  • 1
  • 11
  • Well, if you don't want to use modular arithmetic, you could simply convert negative indices to their positive equivalent before checking. It might be a bit more intuitive, although honestly either method looks fine. You could also just use a `try/except` to catch these errors and just throw indices at it. I'd recommend the latter since then you don't have to bother checking for array length either – user3483203 Sep 25 '18 at 16:08
  • Would `try/except` really work? I know that I can set all of my indices to be non-negative, but this code will be further developed and used by other people. So I want it to be rather robust and able to check for and handle these things. I want to be able to work with negative indices but explain what's happening if `start_index > end_index` accounting for negatives. – LukeC92 Sep 25 '18 at 16:16
  • Perhaps I should mention that the check is done when the indices are first set, they're actually used later in the code. – LukeC92 Sep 25 '18 at 16:22
  • If all you're doing is making sure that that `start_index <= end_index`, you could do something like `array[start_index:end_index].size >= 0`, where `array` is a 1D Numpy array. For N-dimensional arrays you'd use something like `array[].shape[dimension] >= 0` – Maxim Belkin Sep 25 '18 at 16:35
  • That does sound like an interesting idea. However mightn't the size be 0 for reasons other than `start_index` being larger than `end_index`? – LukeC92 Sep 25 '18 at 19:40

0 Answers0