*This tutorial was generated from a Jupyter notebook. You can download the notebook here.*

In [2]:

```
# NumPy, the engine of scientific computing
import numpy as np
# We'll demo a couple SciPy modules
import scipy.special
```

`re`

and `os`

) and from outside the standard library (`pytest`

). In this lesson, we will learn about **NumPy**, arguably *the* most important package for scientific computing. NumPy is part of the **SciPy stack**, a collection of packages for doing various scientific computations. Most of the SciPy stack is built on NumPy and its power `ndarray`

data type. We will devote the entire next lesson to `ndarray`

s, but for now, we will take a brief tour through what NumPy and SciPy offer.

The SciPy stack consists of the following core packages.

Package | Description |
---|---|

NumPy | Base routines and classes for handling data and numerical calculation |

SciPy | Expansive set of tools for scientific calculation |

matplotlib | Plotting library |

IPython | The interactive Python console you already know and love |

Pandas | A powerful data analysis library |

SymPy | Symbolic mathematics library |

With the exception of SymPy, we will use all of these extensively in the next few days. In this lesson, we will show some of the basic features of NumPy and SciPy.

Importantly, everything in the SciPy stack is BSD licensed. This is a very permissive license, which basically means you can do whatever you want when using the code. You just need to include the license if you redistribute it.

Outside of this SciPy stack are important projects that either are too specific to be included in the monolithic SciPy stack, or are still under active development. Importantly, this includes `scikit-image`

, a package for image processing, which we will use later in the course. The new `scikit-bio`

is still in the nascent stages of development and promises to be excellent. We will not use it in the course, since it currently does not run on Windows. We will instead use Biopython, which is a mature package for parsing data in a bioinformatics context.

The central object for NumPy and SciPy is the `ndarray`

, commonly referred to as a "NumPy array." This is an array object that is convenient for scientific computing. We will go over it in depth in the next lesson, but for now, let's just create some NumPy arrays and see how operators work on them.

Just like with type conversions with lists, tuples, and other data types we've looked at, we can convert a list to a NumPy array using

```
np.array()
```

Note that above we imported the NumPy package "`as`

`np`

". This is for convenience; it allow us to use `np`

as a prefix instead of `numpy`

. NumPy is in **very** widespread use, and the convention is to use the `np`

abbreviation.

In [4]:

```
# Create a NumPy array from a list
my_ar = np.array([1, 2, 3, 4])
# Look at it
my_ar
```

Out[4]:

In [9]:

```
# The data type of stored entries
my_ar.dtype
```

Out[9]:

In [11]:

```
# The shape of the array
my_ar.shape
```

Out[11]:

There are also lots of methods. Here are just a few.

In [13]:

```
print(my_ar.max())
print(my_ar.min())
print(my_ar.sum())
print(my_ar.mean())
print(my_ar.std())
```

There are many other ways to make NumPy arrays besides just converting lists or tuples. Below are some examples.

In [3]:

```
# How long our arrays will be
n = 10
# Make a NumPy array of length n filled with zeros
np.zeros(n)
```

Out[3]:

In [4]:

```
# Make a NumPy array of length n filled with ones
np.ones(n)
```

Out[4]:

In [5]:

```
# Make an empty NumPy array of length n (will show zeros when displayed)
np.empty(n)
```

Out[5]:

In [6]:

```
# Make a NumPy array filled with zeros the same shape as another NumPy array
my_ar = np.array([[1, 2], [3, 4]])
np.zeros_like(my_ar)
```

Out[6]:

So far, we have not done much mathematics with Python. We have done some adding and divison, but nothing like computing a logarithm, cosine, or even square roots. Check it out!

In [15]:

```
# Exponential
np.exp(my_ar)
```

Out[15]:

In [16]:

```
# Cosine
np.cos(my_ar)
```

Out[16]:

In [17]:

```
# Square root
np.sqrt(my_ar)
```

Out[17]:

We can even do some matrix operations, like dot products.

In [19]:

```
np.dot(my_ar, my_ar)
```

Out[19]:

NumPy also has useful attributes, like `np.pi`

.

In [18]:

```
np.pi
```

Out[18]:

SciPy actually began life as a library of special functions that operate on NumPy arrays. For example, we can compute an error function, we can use the `scipy.special`

module, which contains lots of special functions. Note that you often have to individually import the SciPy module you want to use, for example with

`import scipy.special`

In [21]:

```
scipy.special.erf(my_ar)
```

Out[21]:

Importantly, NumPy and SciPy routines are often *fast*. To understand why, we need to think a bit about how your computer actually runs code you write.

We have touched on the fact that Python is an **interpreted language**. This means that the Python interpreter reads through your code, line by line, translates the instructions into machine code, and then these are executed. As an interpreted langauge, code is often much easier to write, and development time is much shorter. It is often easier to debug. By contrast, **compiled languages** (the dominant ones being Fortran, C, and C++), your entire code is translated into machine language before you ever run it. When you execute your program, it is already in machine langauge. As a result, compiled code is often much faster than interpreted code. The speed difference depends largely on the task at hand, but is over a 100 to 1000-fold difference.

First, we'll demonstrate the difference between compiled and interpreted languages by looking at a function to sum the elements of an array. Note that Python is dynamically typed, so the function below works for multiple data types, but the C function works only for double precision floating point numbers.

In [24]:

```
# Python code to sum an array and print the result to the screen
print(sum(my_ar))
```

`main`

to call it. You should notice the difference in complexit of the code. Interpreted code is very often much easier to write!

Under the hood, when you call a NumPy or SciPy function, or use one of the methods, the Python interpreter passes the arrays into pre-compiled functions. (They are usually C or Fortran functions.) That means that you get to use an interpreted language with near-compiled speed! We can demonstrate the speed by comparing an explicit sum of elements of an array using a Python ** for** loop versus NumPy. We will use the

`np.random`

module to generate a large array of random numbers (we will visit random number generation in a coming tutorial). We then use the `%timeit`

magic function of IPython to time the execution of the sum of the elements of the array.In [43]:

```
# Make array of 10,000 random numbers
x = np.random.random(10000)
# Sum with Python for loop
def python_sum(x):
x_sum = 0.0
for y in x:
x_sum += y
return x_sum
# Test speed
%timeit python_sum(x)
```

Now we'll do the same test with the NumPy implementation.

In [44]:

```
%timeit x.sum()
```

Wow! We went from 1 millisecond to 6 *micro*seconds! That's a factor of about 170!

If you are writing code, and you think to yourself, "This seems like a pretty common things to do," there is a good chance the someone really smart has written code to do it. If it's something numerical, there is a good chance it is in NumPy or SciPy. **Use these packages.** Do not reinvent the wheel. It is very rare you can beat them for performance, error checking, etc.

Furthermore, NumPy and SciPy are very well unit tested. In general, you do not need to write unit tests for well-established packages. Obviously, if you use NumPy or SciPy within your own functions, you still need to unit test what you wrote.