Python Numpy Tutorial From Stanford
This tutorial was contributed by Justin Johnson.
Python is a great general-purpose programming language on its own, but with the help of a few popular libraries (numpy, scipy, matplotlib) it becomes a powerful environment for scientific computing.
Python is a high-level, dynamically typed multiparadigm programming language. Python code is often said to be almost like pseudocode, since it allows you to express very powerful ideas in very few lines of code while being very readable. As an example, here is an implementation of the classic quicksort algorithm in Python:
|
|
[1, 1, 2, 3, 6, 8, 10]
There are currently two different supported versions of Python, 2.7 and 3.6. Somewhat confusingly, Python 3.0 introduced many backwards-incompatible changes to the language, so code written for 2.7 may not work under 3.6 and vice versa. For this class all code will use Python 3.6.
You can check your Python version at the command line by running python –version.
Basic data typesLike most languages, Python has a number of basic types including integers, floats, booleans, and strings. These data types behave in ways that are familiar from other programming languages.
Numbers: Integers and floats work as you would expect from other languages:
|
|
3
4
9
4
8
2.5 3.5 5.0 6.25
Note that unlike many languages, Python does not have unary increment (
x++
) or decrement (x--
) operators.Python also has built-in types for complex numbers; you can find all of the details in the documentation.
Booleans: Python implements all of the usual operators for Boolean logic, but uses English words rather than symbols (&&, ||, etc.):
|
|
False
True
Strings: Python has great support for strings:
|
|
hello
5
hello world
hello 12 world
String objects have a bunch of useful methods; for example:
|
|
Hello
HELLO
hello
hello
he(ell)(ell)o
world
Containers
Python includes several built-in container types: lists, dictionaries, sets, and tuples.
ListsA list is the Python equivalent of an array, but is resizeable and can contain elements of different types:
|
|
[3, 1, 2] 2
2
[3, 1, 'foo']
[3, 1, 'foo', 'bar']
bar [3, 1, 'foo']
Slicing: In addition to accessing list elements one at a time, Python provides concise syntax to access sublists; this is known as slicing:
|
|
[0, 1, 2, 3, 4]
[2, 3]
[2, 3, 4]
[0, 1]
[0, 1, 2, 3, 4]
[0, 1, 2, 3]
[0, 1, 8, 9, 4]
If you want access to the index of each element within the body of a loop, use the built-in enumerate function:
|
|
1: cat
2: dog
3: monkey
Dictionaries
A dictionary stores (key, value) pairs, similar to a Map in Java or an object in Javascript. You can use it like this:
|
|
True
N/A
{'dog': 'furry'}
Loops: It is easy to iterate over the keys in a dictionary:
|
|
a person has 2 legs
a cat has 4 legs
a spider has 8 legs
If you want access to keys and their corresponding values, use the items method:
|
|
a person has 2 legs
a cat has 4 legs
a spider has 8 legs
Dictionary comprehensions: These are similar to list comprehensions, but allow you to easily construct dictionaries. For example:
|
|
{0: 0, 2: 4, 4: 16}
Sets
A set is an unordered collection of distinct elements. As a simple example, consider the following:
|
|
True
False
True
3
3
2
Loops: Iterating over a set has the same syntax as iterating over a list; however since sets are unordered, you cannot make assumptions about the order in which you visit the elements of the set:
TuplesA tuple is an (immutable) ordered list of values. A tuple is in many ways similar to a list; one of the most important differences is that tuples can be used as keys in dictionaries and as elements of sets, while lists cannot. Here is a trivial example:
|
|
{(0, 1): 0, (1, 2): 1, (2, 3): 2, (3, 4): 3, (4, 5): 4, (5, 6): 5, (6, 7): 6, (7, 8): 7, (8, 9): 8, (9, 10): 9}
<class 'tuple'>
5
1
Functions
Python functions are defined using the def keyword. For example:
|
|
negative
zero
positive
Classes
The syntax for defining classes in Python is straightforward:
|
|
Hello, Fred
HELLO, FRED!
Numpy
Numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays. If you are already familiar with MATLAB, you might find this tutorial useful to get started with Numpy.
ArraysA numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension.
We can initialize numpy arrays from nested Python lists, and access elements using square brackets:
|
|
<class 'numpy.ndarray'>
(3,)
1 2
[5 2 3]
(2, 3)
1
Numpy also provides many functions to create arrays:
|
|
[[ 0. 0.]
[ 0. 0.]]
[[ 1. 1.]]
[[7 7]
[7 7]]
[[ 1. 0.]
[ 0. 1.]]
[[ 0.91141318 0.78561508]
[ 0.37697922 0.9396488 ]]
Array indexing
Numpy offers several ways to index into arrays.
Slicing: Similar to Python lists, numpy arrays can be sliced. Since arrays may be multidimensional, you must specify a slice for each dimension of the array:
|
|
[[2 3]
[6 7]]
2
[[77 3]
[ 6 7]]
77
You can also mix integer indexing with slice indexing. However, doing so will yield an array of lower rank than the original array. Note that this is quite different from the way that MATLAB handles array slicing:
|
|
[5 6 7 8] (4,)
[[5 6 7 8]] (1, 4)
[ 2 6 10] (3,)
[ 3 7 11] (3,)
Integer array indexing: When you index into numpy arrays using slicing, the resulting array view will always be a subarray of the original array. In contrast, integer array indexing allows you to construct arbitrary arrays using the data from another array. Here is an example:
|
|
[1 4 5]
[1 4 5]
[2 2]
[2 2]
One useful trick with integer array indexing is selecting or mutating one element from each row of a matrix:
|
|
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
[ 1 6 7 11]
[[11 2 3]
[ 4 5 16]
[17 8 9]
[10 21 12]]
Boolean array indexing: Boolean array indexing lets you pick out arbitrary elements of an array. Frequently this type of indexing is used to select the elements of an array that satisfy some condition. Here is an example:
|
|
[[False False]
[ True True]
[ True True]]
[3 4 5 6]
[3 4 5 6]
Datatypes
Every numpy array is a grid of elements of the same type. Numpy provides a large set of numeric datatypes that you can use to construct arrays. Numpy tries to guess a datatype when you create an array, but functions that construct arrays usually also include an optional argument to explicitly specify the datatype. Here is an example:
|
|
int32
float64
int64
Array math
Basic mathematical functions operate elementwise on arrays, and are available both as operator overloads and as functions in the numpy module:
|
|
[[ 6. 8.]
[ 10. 12.]]
[[ 6. 8.]
[ 10. 12.]]
[[-4. -4.]
[-4. -4.]]
[[-4. -4.]
[-4. -4.]]
[[ 5. 12.]
[ 21. 32.]]
[[ 5. 12.]
[ 21. 32.]]
[[ 0.2 0.33333333]
[ 0.42857143 0.5 ]]
[[ 0.2 0.33333333]
[ 0.42857143 0.5 ]]
[[ 1. 1.41421356]
[ 1.73205081 2. ]]
Note that unlike MATLAB, *
is elementwise multiplication, not matrix multiplication. We instead use the dot
function to compute inner products of vectors, to multiply a vector by a matrix, and to multiply matrices. dot
is available both as a function in the numpy module and as an instance method of array objects:
|
|
219
219
[29 67]
[29 67]
[[19 22]
[43 50]]
[[19 22]
[43 50]]
Numpy provides many useful functions for performing computations on arrays; one of the most useful is sum
:
|
|
10
[4 6]
[3 7]
You can find the full list of mathematical functions provided by numpy in the documentation.
Apart from computing mathematical functions using arrays, we frequently need to reshape or otherwise manipulate data in arrays. The simplest example of this type of operation is transposing a matrix; to transpose a matrix, simply use the T
attribute of an array object:
|
|
[[1 2]
[3 4]]
[[1 3]
[2 4]]
[1 2 3]
[1 2 3]
Broadcasting
Broadcasting is a powerful mechanism that allows numpy to work with arrays of different shapes when performing arithmetic operations. Frequently we have a smaller array and a larger array, and we want to use the smaller array multiple times to perform some operation on the larger array.
For example, suppose that we want to add a constant vector to each row of a matrix. We could do it like this:
|
|
[[0 0 0]
[0 0 0]
[0 0 0]
[0 0 0]]
|
|
[[ 2 2 4]
[ 5 5 7]
[ 8 8 10]
[11 11 13]]
This works; however when the matrix x is very large, computing an explicit loop in Python could be slow. Note that adding the vector v to each row of the matrix x is equivalent to forming a matrix vv by stacking multiple copies of v vertically, then performing elementwise summation of x and vv. We could implement this approach like this:
|
|
[[1 0 1]
[1 0 1]
[1 0 1]
[1 0 1]]
|
|
[[[1 0 1 1 0 1 1 0 1]
[1 0 1 1 0 1 1 0 1]]
[[1 0 1 1 0 1 1 0 1]
[1 0 1 1 0 1 1 0 1]]
[[1 0 1 1 0 1 1 0 1]
[1 0 1 1 0 1 1 0 1]]
[[1 0 1 1 0 1 1 0 1]
[1 0 1 1 0 1 1 0 1]]]
|
|
[[ 2 2 4]
[ 5 5 7]
[ 8 8 10]
[11 11 13]]
Numpy broadcasting allows us to perform this computation without actually creating multiple copies of v. Consider this version, using broadcasting:
|
|
[[ 2 2 4]
[ 5 5 7]
[ 8 8 10]
[11 11 13]]
The line y = x + v works even though x has shape (4, 3) and v has shape (3,) due to broadcasting; this line works as if v actually had shape (4, 3), where each row was a copy of v, and the sum was performed elementwise.
|
|
[[ 4 5]
[ 8 10]
[12 15]]
|
|
[[2 4 6]
[5 7 9]]
|
|
[[ 5 6 7]
[ 9 10 11]]
|
|
[[ 5 6 7]
[ 9 10 11]]
|
|
[[ 2 4 6]
[ 8 10 12]]