Entry
When using NumPy, how can I use an integer variable as an index for an array created using array()?
Nov 17th, 2007 09:34
Harry Parker, Ben, http://numpy.scipy.org/ http://numpy.scipy.org/numpydoc/numdoc.htm
A simple complete example:
In [1]: from numpy import array
In [2]: a = array([0,5,10,15,20])
In [3]: i = 2
In [4]: a[i]
Out[4]: 10
Following is a short excerpt from the "Array Basics" chapter of
"Numerical Python", found at http://numpy.scipy.org/numpydoc/numdoc.htm
, your best starting point for learning NumPy. Just change every
reference of "numeric" in the sample code of this old document to
"numpy". (See http://numpy.scipy.org/ for the full story.)
Getting and Setting array values
Just like other Python sequences, array contents are manipulated with
the [] notation. For rank-1 arrays, there are no differences between
list and array notations:
>>> a = arrayrange(10)
>>> print a[0] # get first element
0
>>> print a[1:5] # get second through fifth element
[1 2 3 4]
>>> print a[-1] # get last element
9
>>> print a[:-1] # get all but last element
[0 1 2 3 4 5 6 7 8]
The first difference with lists comes with multidimensional indexing. If
an array is multidimensional (of rank > 1), then specifying a single
integer index will return an array of dimension one less than the
original array.
>>> a = arrayrange(9)
>>> a.shape = (3,3)
>>> print a
[[0 1 2]
[3 4 5]
[6 7 8]]
>>> print a[0] # get first row, not first element!
[0 1 2]
>>> print a[1] # get second row
[3 4 5]
To get to individual elements in a rank-2 array, one specifies both
indices separated by commas:
>>> print a[0,0] # get elt at first row, first column
0
>>> print a[0,1] # get elt at first row, second column
1
>>> print a[1,0] # get elt at second row, first column
3
>>> print a[2,-1] # get elt at third row, last column
8