Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpacking tuples/arrays/lists as indices for Numpy Arrays

Tags:

I would love to be able to do

>>> A = numpy.array(((1,2),(3,4))) >>> idx = (0,0) >>> A[*idx] 

and get

1 

however this is not valid syntax. Is there a way of doing this without explicitly writing out

>>> A[idx[0], idx[1]] 

?

EDIT: Thanks for the replies. In my program I was indexing with a Numpy array rather than a tuple and getting strange results. Converting to a tuple as Alok suggests does the trick.

like image 884
ntimes Avatar asked Mar 15 '10 03:03

ntimes


People also ask

Can you unpack NumPy array?

To unpack elements of a uint8 array into a binary-valued output array, use the numpy. unpackbits() method in Python Numpy. The result is binary-valued (0 or 1). The axis is the dimension over which bit-unpacking is done.

Can you convert a list to a NumPy array?

Lists can be converted to arrays using the built-in functions in the Python numpy library. numpy provides us with two functions to use when converting a list into an array: numpy. array()

What is NumPy array indexing?

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

What is indexing and slicing in NumPy?

Numpy with Python Three types of indexing methods are available − field access, basic slicing and advanced indexing. Basic slicing is an extension of Python's basic concept of slicing to n dimensions. A Python slice object is constructed by giving start, stop, and step parameters to the built-in slice function.


2 Answers

It's easier than you think:

>>> import numpy >>> A = numpy.array(((1,2),(3,4))) >>> idx = (0,0) >>> A[idx] 1 
like image 52
Vicki Laidler Avatar answered Sep 21 '22 06:09

Vicki Laidler


Try

A[tuple(idx)] 

Unless you have a more complex use case that's not as simple as this example, the above should work for all arrays.

like image 36
Alok Singhal Avatar answered Sep 18 '22 06:09

Alok Singhal