Performance Zone is brought to you in partnership with:

Mark is a graph advocate and field engineer for Neo Technology, the company behind the Neo4j graph database. As a field engineer, Mark helps customers embrace graph data and Neo4j building sophisticated solutions to challenging data problems. When he's not with customers Mark is a developer on Neo4j and writes his experiences of being a graphista on a popular blog at http://markhneedham.com/blog. He tweets at @markhneedham. Mark is a DZone MVB and is not an employee of DZone and has posted 520 posts at DZone. You can read more from them at their website. View Full User Profile

Python/numpy: Selecting values by multiple indices

01.31.2013
| 1100 views |
  • submit to reddit

As I mentioned in my previous post I’ve been playing around with numpy and I wanted to get the values of a collection of different indices in a 2D array.

If we had a 2D array that looked like this:

>>> x = arange(20).reshape(4,5)
>>> x
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

I knew that it was possible to retrieve the first 3 rows by using the following code:

>>> x[0:3]
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

What I wanted to do, however, was retrieve the 1st, 3rd and 4th rows which we can do by passing a collection to the array lookup function:

>>> x[[0,2,3]]
array([[ 0,  1,  2,  3,  4],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

My collection of indices was actually in a tuple so I needed to use the list function to convert it to the appropriate data structure first:

>>> x[list((0,2,3))]
array([[ 0,  1,  2,  3,  4],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

Pretty neat!



Published at DZone with permission of Mark Needham, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)