1

I have high dimension numpy array, the dimension of the array is not fixed. I need to retrieve the value with a index list, the length of the index list is the same as the dimension of the numpy array.

In other words, I need a function:

def get_value_by_list_index(target_array, index_list):
  # len(index_list) = target_array.ndim
  # target array can be in any dimension
  # return the element at index specified on index list

For example, for a 3-dimension array, data and a list [i1, i2, i3], I the function should return data[i1][i2][i3].

Is there a good way to achieve this task?

4
  • target_array[tuple(index_list)] which is the same as target_array[i1,i2,i3] Commented Mar 21, 2022 at 21:24
  • @hpaulj uff, I didn't even know that; what an API nightmare: let idx=[1,2] be our index list, then arr[idx] gives the second and third row of a matrix, but if idx=(1,2), the same statement yields the second row, third column element Commented Mar 21, 2022 at 21:28
  • Often in python, list and tuple can be used interchangably, but in array indexing the difference is significant. It's the comma that makes a tuple, more so than the (), which are just used to reduce ambiguities. @MarcusMüller Commented Mar 21, 2022 at 21:45
  • @hpaulj fully aware of that, it's just that the type sensitivity to the index container being a tuple or any other iterable is a bit of a footgun if you're passing these around through an API. This is more of a realization than a hm, numpy critique, I guess. Commented Mar 21, 2022 at 21:50

1 Answer 1

1

If you know the ndarray is actually containing a type that is just a number well-representable by python types:

source_array.item(*index_iterable)

will do the same.

If you need to work with ndarrays of more complex types that might not have a python built-in type representation, things are harder.

You could implement exactly what you sketch in your comment:

data[i1][i2][i3]
# note that I didn't like the name of your function
def get_value_by_index_iterable(source_array, index_iterable):
  subarray = source_array
  for index in index_iterable:
    subarray = subarray[index]
  return subarray
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.