Python and Numpy

Tutorial Video

NumPy: The Numerical Python Library

For science, mathematics and engineering the numeric Python library is fundamental. This library makes it far easier to work with arrays of numbers and has a large number of numerical functions for working with numerical arrays.

Importing NumPy

To use the numerical python library numpy we need to import it. As it is commonly used and referenced, it is usually imported as a two letter abbreviation at the top of a Python script:

Python

It can be imported at the top of a script or it can be imported by typing directly into the console.

If we try to use numpy without running the script.

We will get the following error:

If we launch the script with the command to import numpy or run the command in the console.

We can access the commands in this case the command np.pi gives the constant π

Which is the value 3.14… as expected.

If we however go to Console and then Restart Kernal, or close Spyder or restart the computer.

Then once again if we try and access any of the commands within the library it won’t be able to.

Always Enabling NumPy

As NumPy and MatPlotLib are so commonly used for plotting, it is also possible to load the libraries by default. To do this select Tools and then Preferences:

To the left hand side select iPython Console:

To the top right select Graphics, then Automatically Load PyLab and NumPy Modules. Also it is recommended to change the Backend to Automatic. Select Apply:

Then OK. Changes will not be made until either the Kernal is restarted, Spyder is closed and reopened or the computer is restarted.

Looking Up All Commands Using Dot and Tab

Next it is worth looking through the library, this can be done by typing either in the script or console, np followed by a dot and then tab:

Python

This will give a large list of entries by alphabetical order; items stating with a capital are listed in alphabetical order first and then all the lower case functions are likewise listed in alphabetical order.

Take your time and scroll through the list by either using the scroll bar or the [↓] and [↑] keys. Scrolling through the list, in the console, we can see the function pi, which will return pi:

We can select it:

And then execute it:

Python
3.141592653589793

pi returns the value of pi, π.

Functions Without Input Arguments

In order to get more information about this command we can type in a question mark followed by the command in the console:

Python
Type:        float
String form: 3.141592653589793
Docstring:   Convert a string or number to a floating point number, if possible.

This prints the help in the console and explains briefly how to use the command.

Likewise we can have a look at

Python
Type:        float
String form: 2.718281828459045
Docstring:   Convert a string or number to a floating point number, if possible.

We can also highlight the e and press [Ctrl] + [ i ] to get the information about the command (i for information).

This shows only the doc string for these basic strings

Since this is a constant, we can just use the command to generate it.

Python
2.718281828459045

Functions with Input Arguments

There are a number of functions that can use a scalar input, for instance the square root function. It is worthwhile reading the help of these:

Python

Doing so prints out all the help in the console and you can take your time to scroll through it.

Call signature:   np.sqrt(*args, **kwargs)
Type:            ufunc
String form:     <ufunc 'sqrt'>
File:            c:\users\pyip\appdata\local\continuum\anaconda3\lib\site-packages\numpy\__init__.py
Docstring:      
sqrt(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Return the non-negative square-root of an array, element-wise.

Parameters
----------
x : array_like
    The values whose square-roots are required.
out : ndarray, None, or tuple of ndarray and None, optional
    A location into which the result is stored. If provided, it must have
    a shape that the inputs broadcast to. If not provided or `None`,
    a freshly-allocated array is returned. A tuple (possible only as a
    keyword argument) must have length equal to the number of outputs.
where : array_like, optional
    Values of True indicate to calculate the ufunc at that position, values
    of False indicate to leave the value in the output alone.
**kwargs
    For other keyword-only arguments, see the
    :ref:`ufunc docs <ufuncs.kwargs>`.

Returns
-------
y : ndarray
    An array of the same shape as `x`, containing the positive
    square-root of each element in `x`.  If any element in `x` is
    complex, a complex array is returned (and the square-roots of
    negative reals are calculated).  If all of the elements in `x`
    are real, so is `y`, with negative elements returning ``nan``.
    If `out` was provided, `y` is a reference to it.
    This is a scalar if `x` is a scalar.

See Also
--------
lib.scimath.sqrt
    A version which returns complex numbers when given negative reals.

Notes
-----
*sqrt* has--consistent with common convention--as its branch cut the
real "interval" [`-inf`, 0), and is continuous from above on it.
A branch cut is a curve in the complex plane across which a given
complex function fails to be continuous.

Examples
--------
np.sqrt([1,4,9])
array([ 1.,  2.,  3.])

np.sqrt([4, -1, -3+4J])
array([ 2.+0.j,  0.+1.j,  1.+2.j])

np.sqrt([4, -1, numpy.inf])
array([  2.,  NaN,  Inf])
Class docstring:
Functions that operate element by element on whole arrays.

To see the documentation for a specific ufunc, use `info`.  For
example, ``np.info(np.sin)``.  Because ufuncs are written in C
(for speed) and linked into Python with NumPy's ufunc facility,
Python's help() function finds this page whenever help() is called
on a ufunc.

A detailed explanation of ufuncs can be found in the docs for :ref:`ufuncs`.

Calling ufuncs:
===============

op(*x[, out], where=True, **kwargs)
Apply `op` to the arguments `*x` elementwise, broadcasting the arguments.

The broadcasting rules are:

* Dimensions of length 1 may be prepended to either array.
* Arrays may be repeated along dimensions of length 1.

Parameters
----------
*x : array_like
    Input arrays.
out : ndarray, None, or tuple of ndarray and None, optional
    Alternate array object(s) in which to put the result; if provided, it
    must have a shape that the inputs broadcast to. A tuple of arrays
    (possible only as a keyword argument) must have length equal to the
    number of outputs; use `None` for uninitialized outputs to be
    allocated by the ufunc.
where : array_like, optional
    Values of True indicate to calculate the ufunc at that position, values
    of False indicate to leave the value in the output alone.  Note that if
    an uninitialized return array is created via the default ``out=None``,
    then the elements where the values are False will remain uninitialized.
**kwargs
    For other keyword-only arguments, see the :ref:`ufunc docs <ufuncs.kwargs>`.

Returns
-------
r : ndarray or tuple of ndarray
    `r` will have the shape that the arrays in `x` broadcast to; if `out` is
    provided, it will be returned. If not, `r` will be allocated and
    may contain uninitialized values. If the function has more than one
    output, then the result will be a tuple of arrays.

However you may not want the help for every command you want to look up filling up your console. Instead it is recommended to type in the command and leave the parenthesis for the input argument(s) open ended.

Python

Here you will see the form of the input arguments.

In our case, we are only interested in the argument (args) which go first and do not care about the optional keyword argument (kwargs).

You can now highlight the command and the open left bracket in this case sqrt(

Then press [Ctrl] + [ i ] to get the information, you can expand the help to the top right in order to read it better. This gives you the on demand information without clogging up your console. So we see the input argument we are interested in is x.

The first example the help gives is a row vector, however we can also use a simple positive scalar input for simplicity. The help also gives an example with a complex number and an infinite number. In our case we can use the function with a scalar input argument of 2:

Python
1.4142135623730951

The answer has a sequence of non-converging numbers following the decimal point. It may be useful to round this number, we can look at the round function. Once again we can type in:

Python

This will give details on the input arguments:

Here we see we have the arg a, which is the number to be rounded, and optional input arguments which have argument names decimal and out. The default values of these latter arguments if not specified are 0 and None.

Once again we can type in the following to print out the help in the console:

Python
Signature:  np.round(a, decimals=0, out=None)
Docstring:
Round an array to the given number of decimals.

See Also
--------
around : equivalent function; see for details.
File:      c:\users\pyip\appdata\local\continuum\anaconda3\lib\site-packages\numpy\core\fromnumeric.py
Type:      function

However in order to avoid clogging up the console, we can highlight the function and press [Ctrl] + [ i ] to get the information

Here we are told the first input argument is our array a, in our case our scalar input argument can directly be input:

Python
1.0

Note in the expression above, the outside brackets ( ) surround the input arguments of round, with the function round being called from the library np (abbreviated from the full library name numpy). The inside brackets ( ) surround the input arguments of the function sqrt and sqrt is once again a function being called from the library np.

In np.sqrt there is a single input argument, the scalar 2. In np.round there is a single input argument np.sqrt(2) and as only a single input argument was specified for np.round, the default setting decimal=0 and out=None were used.

A second input argument to round can be specified as 1 to round to 1 decimal place. In this case the comma , is used to separate out the two input arguments.

Take the time to understand calling functions from the np library using the dot . aswell as the use of ( ) to surround input arguments and the use of , to separate out the input arguments.

Python
1.4

If instead we wanted 2 decimal places:

Python
1.41

Note that we do not need to use the argument name decimal, merely placing it in the correct order works. We can also look at the function power. Once again looking up help for this function we can see a description:

Python

This unnecessarily clogs up the console.

Call signature:  np.power(*args, **kwargs)
Type:            ufunc
String form:     <ufunc 'power'>
File:            c:\users\pyip\appdata\local\continuum\anaconda3\lib\site-packages\numpy\__init__.py
Docstring:      
power(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

First array elements raised to powers from second array, element-wise.

Raise each base in `x1` to the positionally-corresponding power in
`x2`.  `x1` and `x2` must be broadcastable to the same shape. Note that an
integer type raised to a negative integer power will raise a ValueError.

Parameters
----------
x1 : array_like
    The bases.
x2 : array_like
    The exponents.
out : ndarray, None, or tuple of ndarray and None, optional
    A location into which the result is stored. If provided, it must have
    a shape that the inputs broadcast to. If not provided or `None`,
    a freshly-allocated array is returned. A tuple (possible only as a
    keyword argument) must have length equal to the number of outputs.
where : array_like, optional
    Values of True indicate to calculate the ufunc at that position, values
    of False indicate to leave the value in the output alone.
**kwargs
    For other keyword-only arguments, see the
    :ref:`ufunc docs <ufuncs.kwargs>`.

Returns
-------
y : ndarray
    The bases in `x1` raised to the exponents in `x2`.
    This is a scalar if both `x1` and `x2` are scalars.

See Also
--------
float_power : power function that promotes integers to float

Examples
--------
Cube each element in a list.

x1 = range(6)
x1
[0, 1, 2, 3, 4, 5]
np.power(x1, 3)
array([  0,   1,   8,  27,  64, 125])

Raise the bases to different exponents.

x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
np.power(x1, x2)
array([  0.,   1.,   8.,  27.,  16.,   5.])

The effect of broadcasting.

x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
x2
array([[1, 2, 3, 3, 2, 1],
       [1, 2, 3, 3, 2, 1]])
np.power(x1, x2)
array([[ 0,  1,  8, 27, 16,  5],
       [ 0,  1,  8, 27, 16,  5]])
Class docstring:
Functions that operate element by element on whole arrays.

To see the documentation for a specific ufunc, use `info`.  For
example, ``np.info(np.sin)``.  Because ufuncs are written in C
(for speed) and linked into Python with NumPy's ufunc facility,
Python's help() function finds this page whenever help() is called
on a ufunc.

A detailed explanation of ufuncs can be found in the docs for :ref:`ufuncs`.

Calling ufuncs:
===============

op(*x[, out], where=True, **kwargs)
Apply `op` to the arguments `*x` elementwise, broadcasting the arguments.

The broadcasting rules are:

* Dimensions of length 1 may be prepended to either array.
* Arrays may be repeated along dimensions of length 1.

Parameters
----------
*x : array_like
    Input arrays.
out : ndarray, None, or tuple of ndarray and None, optional
    Alternate array object(s) in which to put the result; if provided, it
    must have a shape that the inputs broadcast to. A tuple of arrays
    (possible only as a keyword argument) must have length equal to the
    number of outputs; use `None` for uninitialized outputs to be
    allocated by the ufunc.
where : array_like, optional
    Values of True indicate to calculate the ufunc at that position, values
    of False indicate to leave the value in the output alone.  Note that if
    an uninitialized return array is created via the default ``out=None``,
    then the elements where the values are False will remain uninitialized.
**kwargs
    For other keyword-only arguments, see the :ref:`ufunc docs <ufuncs.kwargs>`.

Returns
-------
r : ndarray or tuple of ndarray
    `r` will have the shape that the arrays in `x` broadcast to; if `out` is
    provided, it will be returned. If not, `r` will be allocated and
    may contain uninitialized values. If the function has more than one
    output, then the result will be a tuple of arrays.

We can instead just type in the command with an open parenthesis

Python

This once gives us the form of the input arguments. We can also have a look at the information by highlighting the function and then pressing [Ctrl] + [ i ]

This will give the information. Here we see we have two input arguments x1 and x2.

In this example we are only looking at scalars, so the following will calculate:

\displaystyle {{3}^{3}}

Python
27

This can be used also in place of the sqrt function above. Once again we can see that the outside brackets ( ) surround the input arguments of round, with the function round being called from the library np (abbreviated from the full library name numpy). The inside brackets ( ) surround the input arguments of the function power and power is once again a function being called from the library np. There are two input arguments for the function power 2 and 1/2, these are once again separated by a comma , and the inside function and its input arguments i.e. np.power(2,1/2) is an input argument alongside 2 for the outside function np.round, once again separated by a comma.

Python
1.41

The power function can also be used to get the cube root or nth root:

Python
3
Advertisements

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.