Advanced Python Arrays  Introducing NumPy 
Written by Alex Armstrong  
Sunday, 21 April 2013  
Page 3 of 3
Integer IndexingNumPy arrays have other tricks when it comes to indexing mostly borrowed from Matlab and Octave. For example you can set up an indexing array of integers and these will be used to select elements along the corresponding dimension. So for example:
picks out the myArray[0,1] and myArray[2,2] i.e.
You can use this technique to access arbitrary sub matrices of elements or regular sub matrices with indexes determined by other matrices. There are lots of rules that govern how the lists of integers are applied i.e. what happens if you don't specify enough lists and so on but they are all obvious defaults. Boolean IndexingThis is another indexing method borrowed from Matlab and Octave. You can use a Boolean array to pick out the elements you want to work with. If the Boolean array has a true element then the element in the array being indexed is selected. Now at first thought this doesn't sound like a very useful option. Why would you go to the trouble of constructing a Boolean array to pick elements from an array? The answer is because it is very easy. One of the things that NumPy introduces is elementwise functions and operations including elementwise comparisons. For example:
produces a Boolean array:
This makes is easy to index an array on a condition. For example, suppose you wanted to set every element of an array smaller than 0.1 to zero:
Now you can see why a Boolean index is useful! Array FunctionsThere are many features of NumPy that are beyond the scope of this introduction but the availability of array functions is one that you need to know about. NumPy provides many apparent redundant copies of functions that are already provided in math or other modules. For example, np.sqrt seems to be identical to math.sqrt but it can be applied to arrays and it will be computed on each element:
gives:
If you want to compute an elementwise function on a NumPy array then check to see if it is provided within NumPy first  there are a lot of functions for general mathematics, bit manipulation and matrix arithmetic. For example to multiply two matrices together, A.B just use
There is so much more to say about NumPy so look out for another installment on working with arrays. Related ArticlesCreating The Python UI With Tkinter Creating The Python UI With Tkinter  The Canvas Widget Head First Python (Book Review) A Concise Introduction to Programming In Python (Book Review)
Comments
or email your comment to: comments@iprogrammer.info
To be informed about new articles on I Programmer, subscribe to the RSS feed, follow us on Google+, Twitter, Linkedin or Facebook or sign up for our weekly newsletter.


Last Updated ( Wednesday, 27 February 2019 ) 