Week 17
NumPy
Last updated
NumPy
Last updated
NumPy (Numerical Python) is an open source Python library that is used in almost every field of science and engineering. It’s the universal standard for working with numerical data in Python, and it’s at the core of the scientific Python and PyData ecosystems. NumPy users include everyone from beginning coders to experienced researchers doing state-of-the-art scientific and industrial research and development. The NumPy API is used extensively in Pandas, SciPy, Matplotlib, scikit-learn, scikit-image and most other data science and scientific Python packages.
The NumPy library contains multidimensional array and matrix data structures (you’ll find more information about this in later sections). It provides ndarray, a homogeneous n-dimensional array object, with methods to efficiently operate on it. NumPy can be used to perform a wide variety of mathematical operations on arrays. It adds powerful data structures to Python that guarantee efficient calculations with arrays and matrices and it supplies an enormous library of high-level mathematical functions that operate on these arrays and matrices.
If you already have Python installed, you can install NumPy with:
or
Any time you want to use a package or library in your code, you first need to make it accessible.
In order to start using NumPy and all of the functions available in NumPy, you’ll need to import it. This can be easily done with this import statement:
(We shorten numpy
to np
in order to save time and also to keep code standardized so that anyone working with your code can easily understand and run it.)
An array is a central data structure of the NumPy library. An array is a grid of values and it contains information about the raw data, how to locate an element, and how to interpret an element. It has a grid of elements that can be indexed in various ways. The elements are all of the same type, referred to as the array dtype
.
An array can be indexed by a tuple of nonnegative integers, by booleans, by another array, or by integers. The rank
of the array is the number of dimensions. The shape
of the array is a tuple of integers giving the size of the array along each dimension.
One way we can initialize NumPy arrays is from Python lists, using nested lists for two- or higher-dimensional data.
For example:
or:
We can access the elements in the array using square brackets like you are used to from lists. When you’re accessing elements, remember that indexing in NumPy starts at 0. That means that if you want to access the first element in your array, you’ll be accessing element “0”.
You might have noticed quite some similarities between Python lists and NumPy arrays. But what is the difference between them exactly, and why would we use arrays?
NumPy gives you an enormous range of fast and efficient ways of creating arrays and manipulating numerical data inside them. While a Python list can contain different data types within a single list, all of the elements in a NumPy array should be homogeneous. The mathematical operations that are meant to be performed on arrays would be extremely inefficient if the arrays weren’t homogeneous.
Why use NumPy?
NumPy arrays are faster and more compact than Python lists. An array consumes less memory and is convenient to use. NumPy uses much less memory to store data and it provides a mechanism of specifying the data types. This allows the code to be optimized even further.
Example: Time comparison between Numpy array and Python lists
The NumPy ndarray class is used to represent both matrices and vectors. A vector is an array with a single dimension (there's no difference between row and column vectors), while a matrix refers to an array with two dimensions. For 3-D or higher dimensional arrays, the term tensor is also commonly used.
This section covers np.array()
, np.zeros()
, np.ones()
, np.empty()
, np.arange()
, np.linspace()
, dtype
To create a NumPy array, you can use the function np.array()
.
All you need to do to create a simple array is pass a list to it. If you choose to, you can also specify the type of data in your list. You can find more information about data types here.
You can visualize your array this way:
Be aware that these visualizations are meant to simplify ideas and give you a basic understanding of NumPy concepts and mechanics. Arrays and array operations are much more complicated than are captured here!
Besides creating an array from a sequence of elements, you can easily create an array filled with 0
’s:
Or an array filled with 1
’s:
Or even an empty array! The function empty
creates an array whose initial content is random and depends on the state of the memory. The reason to use empty
over zeros
(or something similar) is speed - just make sure to fill every element afterwards!
You can create an array with a range of elements:
And even an array that contains a range of evenly spaced intervals. To do this, you will specify the first number, last number, and the step size.
You can also use np.linspace()
to create an array with values that are spaced linearly in a specified interval:
Specifying your data type
While the default data type is floating point (np.float64
), you can explicitly specify which data type you want using the dtype
keyword.
NumPy offers the random
module to work with random numbers.
Generate a random integer from 0 to 100:
Generate a 1-D array containing 5 random integers from 0 to 100:
Generate a random float from 0 to 1:
Generate a 1-D array containing 5 random floats:
You can pass Python lists of lists to create a 2-D array (or “matrix”) to represent them in NumPy.
Most functions we have mentioned so far work for matrices as well. For example, here is how to generate a 2-D array with 3 rows, each row containing 5 random integers from 0 to 100:
Generate a 2-D array with 3 rows, each row containing 5 random numbers:
You can index and slice NumPy arrays in the same ways you can slice Python lists.
You can visualize it this way:
You may want to take a section of your array or specific array elements to use in further analysis or additional operations. To do that, you’ll need to subset, slice, and/or index your arrays.
Indexing and slicing operations are useful when you’re manipulating matrices as well. You can then slice or index both dimensions:
You can also index on a single dimension while keeping the other fixed:
If you want to select values from your array that fulfil certain conditions, it’s straightforward with NumPy. For example, if you start with this array:
You can easily print all of the values in the array that are less than 5.
You can also select, for example, numbers that are equal to or greater than 5, and use that condition to index an array.
You can select elements that are divisible by 2:
Or you can select elements that satisfy two conditions using the &
and |
operators:
This is called Boolean Indexing and can be extremely useful. This might look like magic, so let's break down why it works. First, you are aware of Booleans, and how you can produce a True
or False
output like so:
Well, similarly you can compare an array with a number, but instead of a single Boolean value, it will return a Boolean value for each element in the array:
Wow! So we get back an array of the same shape as a
but instead with True
or False
(and therefore datatype 'bool') as elements depending on whether the element in the same place satisfies the comparison. Then we can use that array to index the original array, which will only give back the elements where the index is True
:
Which is what we got before as well! This works only if the shapes of both the index and the array are the same. Let's discuss how to get the shape of an array next.
This section covers ndarray.ndim
, ndarray.size
, ndarray.shape
ndarray.ndim
will tell you the number of axes, or dimensions, of the array.
ndarray.size
will tell you the total number of elements of the array. This is the product of the elements of the array’s shape.
ndarray.shape
will display a tuple of integers that indicate the number of elements stored along each dimension of the array. If, for example, you have a 2-D array with 2 rows and 3 columns, the shape of your array is (2, 3)
.
For example, if you create this array:
To find the number of dimensions of the array, run:
To find the total number of elements in the array, run:
And to find the shape of your array, run:
This section covers arr.reshape()
, arr.transpose()
, arr.T
It’s common to need to transpose your matrices. NumPy arrays have the property T
that allows you to transpose a matrix.
You may also need to switch the dimensions of a matrix. This can happen when, for example, you have a model that expects a certain input shape that is different from your dataset. This is where the reshape
method can be useful. You simply need to pass in the new dimensions that you want for the matrix.
You can also use .transpose()
to reverse or change the axes of an array according to the values you specify.
If you start with this array:
You can transpose your array with arr.transpose()
.
You can also use arr.T
:
This section covers .flatten()
, ravel()
There are two popular ways to flatten an array: .flatten()
and .ravel()
. The primary difference between the two is that the new array created using ravel()
is actually a reference to the parent array (i.e., a “view”). This means that any changes to the new array will affect the parent array as well. Since ravel
does not create a copy, it’s memory efficient.
If you start with this array:
You can use flatten
to flatten your array into a 1D array.
When you use flatten
, changes to your new array won’t change the parent array.
For example:
But when you use ravel
, the changes you make to the new array will affect the parent array.
For example:
This section covers np.vstack()
, np.hstack()
, np.concatenate
, np.hsplit()
, .view()
, copy()
You can combine arrays by stacking them, both vertically and horizontally. Let’s say you have two arrays, a1
and a2
:
You can stack them vertically with vstack
:
Or stack them horizontally with hstack
:
Similarly, you could concatenate them with np.concatenate()
.
Or, if you start with these arrays:
You can concatenate them with:
Or:
In 2D this achieves the same as with hstack
or vstack
but if you ever need it, concatenate also works for higher dimensions!
You can use the view
method to create a new array object that looks at the same data as the original array (a shallow copy).
Views are an important NumPy concept! NumPy functions, as well as operations like indexing and slicing, will return views whenever possible. This saves memory and is faster (no copy of the data has to be made). However it’s important to be aware of this - modifying data in a view also modifies the original array!
Let’s say you create this array:
Now we create an array b1
by slicing a
and modify the first element of b1
. This will modify the corresponding element in a
as well!
Using the copy
method will make a complete copy of the array and its data (a deep copy). To use this on your array, you could run:
We have seen how to create an index arrays and some basic ways to transform them. Next to these, there is a large amount of built-in array operations NumPy that can be used to modify arrays and gain insight in their data. We will cover some of those operations here, the ones that are commonly used. Do keep in mind that this is just touching the surface: NumPy is a huge library and many things are built-in. If you wonder if a function exists, Google it, and chances are you might find it!
This section covers addition, subtraction, multiplication, division
Once you’ve created your arrays, you can start to work with them. Let’s say, for example, that you’ve created two arrays, one called “data” and one called “ones”
You can add the arrays together with the plus sign.
You can, of course, do more than just addition!
There are times when you might want to carry out an operation between an array and a single number (also called an operation between a vector and a scalar) or between arrays of two different sizes. For example, your array (we’ll call it “data”) might contain information about distance in miles but you want to convert the information to kilometres. You can perform this operation with:
NumPy understands that the multiplication should happen with each cell. That concept is called broadcasting. Broadcasting is a mechanism that allows NumPy to perform operations on arrays of different shapes. The dimensions of your array must be compatible, for example, when the dimensions of both arrays are equal or when one of them is 1. If the dimensions are not compatible, you will get a ValueError
.
This section covers maximum, minimum, sum, mean, product, standard deviation, and more
NumPy also performs aggregation functions. In addition to min
, max
, and sum
, you can easily run mean
to get the average, prod
to get the result of multiplying the elements together, std
to get the standard deviation, and more.
Let’s start with this array, called “a”
It’s very common to want to aggregate along a row or column. By default, every NumPy aggregation function will return the aggregate of the entire array. To find the sum or the minimum of the elements in your array, run:
Or:
You can specify on which axis you want the aggregation function to be computed. For example, you can find the minimum value within each column by specifying axis=0
.
The four values listed above correspond to the number of columns in your array. With a four-column array, you will get four values as your result.
You can aggregate matrices the same way you aggregated vectors:
You can aggregate all the values in a matrix and you can aggregate them across columns or rows using the axis
parameter:
Similarly to arrays, you can add and multiply matrices using arithmetic operators if you have two matrices that are the same size:
You can do these arithmetic operations on matrices of different sizes, but only if one matrix has only one column or one row. In this case, NumPy will use its broadcast rules for the operation.
Be aware that when NumPy prints N-dimensional arrays, the last axis is looped over the fastest while the first axis is the slowest.
This section covers np.sort()
Sorting an element is simple with np.sort()
. You can specify the axis, kind, and order when you call the function.
If you start with this array:
You can quickly sort the numbers in ascending order with:
If you start with these arrays:
Most of the visualisations used in this material section is from this illustrated NumPy guide. If you would like to read up some more, you can check it out for a slightly different explanation. Do note that in contains more content than we expect from you to know.
Pandas is a Python library used for working with data sets.
It has functions for analyzing, cleaning, exploring, and manipulating data.
The name "Pandas" has a reference to both "Panel Data", and "Python Data Analysis" and was created by Wes McKinney in 2008.
Pandas allows us to analyze big data and make conclusions based on statistical theories.
Pandas can clean messy data sets, and make them readable and relevant.
Relevant data is very important in data science.
We’ll start with a quick, non-comprehensive overview of the fundamental data structures in pandas to get you started. The fundamental behavior about data types, indexing, and axis labeling / alignment apply across all of the objects. To get started, import NumPy and load pandas into your namespace:
Series
is a one-dimensional labelled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). The axis labels are collectively referred to as the index.
A Pandas Series is like a column in a table. It is a one-dimensional array holding data of any type.
The basic method to create a Series is to call:
If nothing else is specified, the values are labeled with their index number. First value has index 0, second value has index 1 etc.
This label can be used to access a specified value.
NaN (not a number) is the standard missing data marker used in pandas.
data
is a scalar value, an index must be provided. The value will be repeated to match the length of index: If data
is an ndarray, index must be the same length as data. If no index is passed, one will be created having values [0, ..., len(data) - 1]
Series
acts very similarly to a ndarray
, and is a valid argument to most NumPy functions. However, operations such as slicing will also slice the index.
A Series is like a fixed-size dict in that you can get and set values by index label:
An example:
dtype
-
Return the dtype object of the underlying data. Pandas will default to the object datatype ('o'
) for strings:
shape
-
Return a tuple of the shape of the underlying data.
axes
- Return a list of the row axis labels.
index
-
The index (axis labels) of the Series.
values
-
Return Series as ndarray or ndarray-like depending on the dtype.
keys
() - Return alias for index.
pd.concat
pd.concat()
can be used for a simple concatenation of Series
or DataFrame
objects, just as np.concatenate()
can be used for simple concatenations of arrays.
append()