NumPy basics
Keywords: gildas-python

Next: Attributes Up: Prerequisites (what you have Previous: Global/local variables and module Contents Index

###
`NumPy` basics

Array handling is provided to Python by the optional package `NumPy`. `NumPy` derives from the older module `Numeric` which documentation is available at `http://nume ric.scipy.org/numpydoc/numdoc.htm`. You will have to pay for the `NumPy` documentation4, but the `Numeric` one may be sufficient to begin handling arrays with Python. You can also find an extensive list of the `NumPy` functions, methods and attributes at `http://www.scipy.org/Numpy_Example_List_With_Doc` .
The type `ndarray` provided by `NumPy` module has a large set of attributes and methods which can help to deal with these objects. This module also brings many useful functions.

    >>> from numpy import array, reshape
    >>> a = reshape(array(range(1,25)),(2,3,4))
    >>>     # integers from 1 to 24 rearranged in a 2x3x4 data cube
    >>> a
    array([[[ 1,  2,  3,  4],
            [ 5,  6,  7,  8],
            [ 9, 10, 11, 12]],
           [[13, 14, 15, 16],
            [17, 18, 19, 20],
            [21, 22, 23, 24]]])
    >>> type(a)
    <type 'numpy.ndarray'>

Basic array elements access may be summarized as follows:

    >>> a[0] # First subarray through first dimension
    array([[ 1,  2,  3,  4],
           [ 5,  6,  7,  8],
           [ 9, 10, 11, 12]])
    >>> a[0][1] # Second subarray through first dimension of subarray 'a[0]'
    array([5, 6, 7, 8])
    >>> a[0][1][2]
    7
    >>> a[0,1,2] # Same as above
    7
    >>> j = (0,1,2)
    >>> a[j] # Tuples are valid indices
    7

    >>> a[:] # All subarrays through first dimension, thus 'a' itself
    array([[[ 1,  2,  3,  4],
            [ 5,  6,  7,  8],
            [ 9, 10, 11, 12]],
           [[13, 14, 15, 16],
            [17, 18, 19, 20],
            [21, 22, 23, 24]]])

    >>> a[0:1] # lower limit is included, upper limit excluded,
               # thus only a[0]
    array([[[ 1,  2,  3,  4],
            [ 5,  6,  7,  8],
            [ 9, 10, 11, 12]]])
    >>> a[:,1:,:2] # All elements through 1st dimension,
                   # all elements except 1st one (0) through 2nd dimension,
                   # 1st two elements (0 and 1) through 3rd dimension:
    array([[[ 5,  6],
            [ 9, 10]],
           [[17, 18],
            [21, 22]]])

Subsections

- Attributes
- Methods
- Functions
- Subarrays and derivates