Numerical Computing with Python and Numpy
This tutorial covers the following topics:
Working with numerical data in Python
Going from Python lists to Numpy arrays
Multi-dimensional Numpy arrays and their benefits
Array operations, broadcasting, indexing, and slicing
Working with CSV data files using Numpy
Working with numerical data
The "data" in Data Analysis typically refers to numerical data, e.g., stock prices, sales figures, sensor measurements, sports scores, database tables, etc. The Numpy library provides specialized data structures, functions, and other tools for numerical computing in Python. Let's work through an example to see why & how to use Numpy for working with numerical data.
Suppose we want to use climate data like the temperature, rainfall, and humidity to determine if a region is well suited for growing apples. A simple approach for doing this would be to formulate the relationship between the annual yield of apples (tons per hectare) and the climatic conditions like the average temperature (in degrees Fahrenheit), rainfall (in millimeters) & average relative humidity (in percentage) as a linear equation.
yield_of_apples = w1 * temperature + w2 * rainfall + w3 * humidity
We're expressing the yield of apples as a weighted sum of the temperature, rainfall, and humidity. This equation is an approximation since the actual relationship may not necessarily be linear, and there may be other factors involved. But a simple linear model like this often works well in practice.
Based on some statical analysis of historical data, we might come up with reasonable values for the weights w1
, w2
, and w3
. Here's an example set of values:
Given some climate data for a region, we can now predict the yield of apples. Here's some sample data:
To begin, we can define some variables to record climate data for a region.
We can now substitute these variables into the linear equation to predict the yield of apples.
In [3]:
Out[3]:
In [4]:
To make it slightly easier to perform the above computation for multiple regions, we can represent the climate data for each region as a vector, i.e., a list of numbers.
In [5]:
The three numbers in each vector represent the temperature, rainfall, and humidity data, respectively.
We can also represent the set of weights used in the formula as a vector.
In [6]:
We can now write a function crop_yield
to calcuate the yield of apples (or any other crop) given the climate data and the respective weights.
In [7]:
In [8]:
Out[8]:
In [9]:
Out[9]:
In [10]:
Out[10]:
Going from Python lists to Numpy arrays
The calculation performed by the crop_yield
(element-wise multiplication of two vectors and taking a sum of the results) is also called the dot product. Learn more about dot product here: https://www.khanacademy.org/math/linear-algebra/vectors-and-spaces/dot-cross-products/v/vector-dot-product-and-vector-length .
The Numpy library provides a built-in function to compute the dot product of two vectors. However, we must first convert the lists into Numpy arrays.
Let's install the Numpy library using the pip
package manager.
In [11]:
Next, let's import the numpy
module. It's common practice to import numpy with the alias np
.
In [12]:
We can now use the np.array
function to create Numpy arrays.
In [13]:
In [14]:
Out[14]:
In [15]:
In [16]:
Out[16]:
Numpy arrays have the type ndarray
.
In [17]:
Out[17]:
In [18]:
Out[18]:
Just like lists, Numpy arrays support the indexing notation []
.
In [19]:
Out[19]:
In [20]:
Out[20]:
Operating on Numpy arrays
We can now compute the dot product of the two vectors using the np.dot
function.
In [21]:
Out[21]:
We can achieve the same result with low-level operations supported by Numpy arrays: performing an element-wise multiplication and calculating the resulting numbers' sum.
In [22]:
Out[22]:
The *
operator performs an element-wise multiplication of two arrays if they have the same size. The sum
method calculates the sum of numbers in an array.
In [23]:
In [24]:
Out[24]:
In [25]:
Out[25]:
Benefits of using Numpy arrays
Numpy arrays offer the following benefits over Python lists for operating on numerical data:
Ease of use: You can write small, concise, and intuitive mathematical expressions like
(kanto * weights).sum()
rather than using loops & custom functions likecrop_yield
.Performance: Numpy operations and functions are implemented internally in C++, which makes them much faster than using Python statements & loops that are interpreted at runtime
Here's a comparison of dot products performed using Python loops vs. Numpy arrays on two vectors with a million elements each.
In [26]:
In [27]:
Out[27]:
In [28]:
Out[28]:
As you can see, using np.dot
is 100 times faster than using a for
loop. This makes Numpy especially useful while working with really large datasets with tens of thousands or millions of data points.
Multi-dimensional Numpy arrays
We can now go one step further and represent the climate data for all the regions using a single 2-dimensional Numpy array.
In [31]:
In [32]:
Out[32]:
If you've taken a linear algebra class in high school, you may recognize the above 2-d array as a matrix with five rows and three columns. Each row represents one region, and the columns represent temperature, rainfall, and humidity, respectively.
Numpy arrays can have any number of dimensions and different lengths along each dimension. We can inspect the length along each dimension using the .shape
property of an array.
Out[33]:
In [34]:
Out[34]:
In [35]:
Out[35]:
In [36]:
In [37]:
Out[37]:
All the elements in a numpy array have the same data type. You can check the data type of an array using the .dtype
property.
In [38]:
Out[38]:
In [39]:
Out[39]:
If an array contains even a single floating point number, all the other elements are also converted to floats.
In [40]:
Out[40]:
We can now compute the predicted yields of apples in all the regions, using a single matrix multiplication between climate_data
(a 5x3 matrix) and weights
(a vector of length 3). Here's what it looks like visually:
You can learn about matrices and matrix multiplication by watching the first 3-4 videos of this playlist: https://www.youtube.com/watch?v=xyAuNHPsq-g&list=PLFD0EB975BA0CC1E0&index=1 .
We can use the np.matmul
function or the @
operator to perform matrix multiplication.
In [41]:
Out[41]:
In [42]:
Out[42]:
Working with CSV data files
Numpy also provides helper functions reading from & writing to files. Let's download a file climate.txt
, which contains 10,000 climate measurements (temperature, rainfall & humidity) in the following format:
This format of storing data is known as comma-separated values or CSV.
CSVs: A comma-separated values (CSV) file is a delimited text file that uses a comma to separate values. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. A CSV file typically stores tabular data (numbers and text) in plain text, in which case each line will have the same number of fields. (Wikipedia)
To read this file into a numpy array, we can use the genfromtxt
function.
In [44]:
In [45]:
Out[45]:
Out[46]:
We can now perform a matrix multiplication using the @
operator to predict the yield of apples for the entire dataset using a given set of weights.
In [47]:
In [48]:
In [49]:
Out[49]:
In [50]:
Out[50]:
Let's add the yields
to climate_data
as a fourth column using the np.concatenate
function.
In [51]:
In [52]:
Out[52]:
There are a couple of subtleties here:
Since we wish to add new columns, we pass the argument
axis=1
tonp.concatenate
. Theaxis
argument specifies the dimension for concatenation.The arrays should have the same number of dimensions, and the same length along each except the dimension used for concatenation. We use the
np.reshape
function to change the shape ofyields
from(10000,)
to(10000,1)
.
Here's a visual explanation of np.concatenate
along axis=1
(can you guess what axis=0
results in?):
The best way to understand what a Numpy function does is to experiment with it and read the documentation to learn about its arguments & return values. Use the cells below to experiment with np.concatenate
and np.reshape
.
Let's write the final results from our computation above back to a file using the np.savetxt
function.
In [53]:
Out[53]:
In [54]:
The results are written back in the CSV format to the file climate_results.txt
.
Numpy provides hundreds of functions for performing operations on arrays. Here are some commonly used functions:
Mathematics:
np.sum
,np.exp
,np.round
, arithemtic operatorsArray manipulation:
np.reshape
,np.stack
,np.concatenate
,np.split
Linear Algebra:
np.matmul
,np.dot
,np.transpose
,np.eigvals
Statistics:
np.mean
,np.median
,np.std
,np.max
How to find the function you need? The easiest way to find the right function for a specific operation or use-case is to do a web search. For instance, searching for "How to join numpy arrays" leads to this tutorial on array concatenation.
You can find a full list of array functions here: https://numpy.org/doc/stable/reference/routines.html
Arithmetic operations, broadcasting and comparison
Numpy arrays support arithmetic operators like +
, -
, *
, etc. You can perform an arithmetic operation with a single number (also called scalar) or with another array of the same shape. Operators make it easy to write mathematical expressions with multi-dimensional arrays.
In [58]:
In [59]:
In [60]:
Out[60]:
In [61]:
Out[61]:
In [62]:
Out[62]:
In [63]:
Out[63]:
In [64]:
Out[64]:
Array Broadcasting
Numpy arrays also support broadcasting, allowing arithmetic operations between two arrays with different numbers of dimensions but compatible shapes. Let's look at an example to see how it works.
In [65]:
In [66]:
Out[66]:
In [67]:
In [68]:
Out[68]:
In [69]:
Out[69]:
When the expression arr2 + arr4
is evaluated, arr4
(which has the shape (4,)
) is replicated three times to match the shape (3, 4)
of arr2
. Numpy performs the replication without actually creating three copies of the smaller dimension array, thus improving performance and using lower memory.
Broadcasting only works if one of the arrays can be replicated to match the other array's shape.
In [70]:
In [71]:
Out[71]:
In [72]:
In the above example, even if arr5
is replicated three times, it will not match the shape of arr2
. Hence arr2 + arr5
cannot be evaluated successfully. Learn more about broadcasting here: https://numpy.org/doc/stable/user/basics.broadcasting.html .
Array Comparison
Numpy arrays also support comparison operations like ==
, !=
, >
etc. The result is an array of booleans.
In [73]:
In [74]:
Out[74]:
In [75]:
Out[75]:
In [76]:
Out[76]:
In [77]:
Out[77]:
Array comparison is frequently used to count the number of equal elements in two arrays using the sum
method. Remember that True
evaluates to 1
and False
evaluates to 0
when booleans are used in arithmetic operations.
Out[78]:
Array indexing and slicing
Numpy extends Python's list indexing notation using []
to multiple dimensions in an intuitive fashion. You can provide a comma-separated list of indices or ranges to select a specific element or a subarray (also called a slice) from a Numpy array.
In [79]:
In [80]:
Out[80]:
In [81]:
Out[81]:
In [82]:
Out[82]:
In [83]:
Out[83]:
In [84]:
Out[84]:
In [85]:
Out[85]:
In [86]:
Out[86]:
In [87]:
The notation and its results can seem confusing at first, so take your time to experiment and become comfortable with it. Use the cells below to try out some examples of array indexing and slicing, with different combinations of indices and ranges. Here are some more examples demonstrated visually:
Other ways of creating Numpy arrays
Numpy also provides some handy functions to create arrays of desired shapes with fixed or random values. Check out the official documentation or use the help
function to learn more.
In [88]:
Out[88]:
In [89]:
Out[89]:
In [90]:
Out[90]:
In [91]:
Out[91]:
In [92]:
Out[92]:
In [93]:
Out[93]:
In [94]:
Out[94]:
In [95]:
Out[95]:
Last updated