1

Numpy has "integer array indexig", which allows to index ndarray with other ndarray or list:

>> A = np.arange(10,20)
>> A[[1,2,3]]
Out[14]: array([11, 12, 13])

Suppose I don't know what is A, which can be either ndarray or Python's list.

Is there any explicit indexing function in numpy, which would allow the same indexing and accept both types?

For example:

>> A = np.arange(10,20)
>> np.get_elements(A, [1,2,3])
Out[14]: array([11, 12, 13])
>> A = range(10,20)
>> np.get_elements(A, [1,2,3])
Out[15]: [11, 12, 13]
3
  • 1
    Use numpy.take. Commented Nov 20, 2017 at 13:23
  • 1
    Do you expect it to return a list if input is a list? A numpy function will first ensure A is an array (eg asarday(A)). Commented Nov 20, 2017 at 15:37
  • Look at operator.itemgetter Commented Nov 20, 2017 at 15:42

1 Answer 1

1
def get_elements(A, idx):
    try:
        return A[idx]
    except TypeError:
        import operator
        return list(operator.itemgetter(*idx)(A))

In [35]: get_elements(np.arange(10), [1,3,4])
Out[35]: array([1, 3, 4])
In [36]: get_elements(np.arange(10).tolist(), [1,3,4])
Out[36]: [1, 3, 4]

itemgetter is just a convenience class. The list comprehension would be just as good

In [39]: [A[i] for i in [1,3,4]]
Out[39]: [1, 3, 4]

A numpy function like take returns an array

In [40]: np.take(A,[1,3,4])
Out[40]: array([1, 3, 4])

which could be converted back into a list if desired.

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.