_prepared by: Cindee Madison
Thanks to: Ariel Rokem, Matt Davis, Justin Kitzes, Katy Huff, Matthew Terry, Scipy Tutorial
Additional Resources
NumPy is a Python package implementing efficient collections of specific types of data (generally numerical), similar to the standard array
module (but with many more features). NumPy arrays differ from lists and tuples in that the data is contiguous in memory. A Python list,
[0, 1, 2]
, in contrast, is actually an array of pointers to Python objects representing each number. This allows NumPy arrays to be
considerably faster for numerical operations than Python lists/tuples.
Numpy provides
extension package to Python for multi-dimensional arrays
closer to hardware (efficiency)
designed for scientific computation (convenience)
Also known as array oriented computing
The Numpy Library contains functions and things
np.sqrt(64) #this is a function
np.pi #this is variable, not a function
np.sin( np.pi ) #a variable passed to a function
# import library, standard convention
import numpy as np
# To see what's in a package, type the name, a period, then hit tab
#np?
#np.
# Some examples of numpy functions and "things":
print(np.sqrt(4))
print(np.pi) # Not a function, just a variable
print(np.sin(np.pi)) # A function on a variable :)
Creating a NumPy array is as simple as passing a sequence to numpy.array:
Numpy arrays are collections of things, all of which must be the same type, that work similarly to lists (as we've described them so far). The most important are:
Arrays can be created from existing collections such as lists, or instantiated "from scratch" in a few useful ways.
arr1 = np.array([1, 2.3, 4])
print(type(arr1))
print(arr1.dtype)
You can also explicitly specify the data-type if the automatically-chosen one would be unsuitable.
arr2 = np.array([1, 2.3, 4], dtype=int)
print(type(arr2))
print(arr2.dtype)
As you might expect, creating a NumPy array this way can be slow, since it must manually convert each element of a list into its equivalent C type (int objects become C ints, etc). There are many other ways to create NumPy arrays, such as
np.identity
np.zeros
np.zeros_like
or by manually specifying the dimensions and type of the array with the low-level creation function:
arr3 = np.ndarray((2, 3, 4), dtype=complex) # Notice : `ndarray`, not `array`!
print(type(arr3))
## what are the values in arr3??
Arrays have a .shape
attribute, which stores the dimensions of the array as a tuple:
print(arr3.shape)
For many of the examples below, we will be using np.arange
which, similar to the Python built-in function range
, returns a NumPy array
of integers from 0 to N-1, inclusive. Like range
, you can also specify a starting value and a step:
arr4 = np.arange(2, 5)
print(arr4)
arr5 = np.arange(1, 5, 2)
print(arr5)
arr6 = np.arange(1, 10, 2)
print arr6
Create an array with values ranging from 0 to 10, in increments of 0.5.
Reminder: get help by typing np.arange?
, np.ndarray?
, np.array?
, etc.
Since numpy exists to perform efficient numerical operations in Python, arrays have all the usual arithmetic operations available to them. These operations are performed element-wise (i.e. the same operation is performed independently on each element of the array).
A = np.arange(5)
B = np.arange(5, 10)
print 'A is ', A
print 'B is ', B
print (A+B)
print(B-A)
print(A*B)
shape
?¶A_10 = np.ones(10)
B_5 = np.zeros(5)
A_10 + B_5
In addition, if one of the arguments is a scalar, that value will be applied to all the elements of the array.
A = np.arange(5)
print(A+10)
print(2*A)
print(A**2)
You can use arrays as vectors and matrices in linear algebra operations
Specifically, you can perform matrix/vector multiplication between arrays, by using the .dot
method, or the np.dot
function:
print A, B
print A.dot(B)
print np.dot(A, B)
Note: This is like the '``' operator in Matlab*
http://en.wikipedia.org/wiki/Dot_product
Given two vectors in 2-space:
a = [1,2]
b = [4,5]
Find the angle between these vectors.
The rotation matrix of $\theta$ angle is a matrix with elements:
[[cos($\theta$), -sin($\theta$],
[sin($\theta$, cos($\theta$)]]
Create a function that takes two 2D-vectors and creates the rotation matrix between them.
For the vector c=[7,8]
, find a vector d
that has the same rotation as b
has relative to a
http://en.wikipedia.org/wiki/Dot_product
We can use a dot product to help us find theta $$\theta$$
$$\mathbf A\cdot\mathbf B = \|\mathbf A\|\,\|\mathbf B\|\cos\theta$$$$\|\mathbf{p}\| = \sqrt{p_1^2+p_2^2+\cdots +p_n^2} = \sqrt{\mathbf{p}\cdot\mathbf{p}}$$Where $$\sqrt{\mathbf{p}\cdot\mathbf{p}}$$ is the square root of the dot product
a = np.array([1,2])
b = np.array([4,5])
def angle_between_vectors(a,b):
"""
find the angle between two vectors
"""
norm_a = np.sqrt(a.dot(a))
norm_b = np.sqrt(b.dot(b))
ab_dot = a.dot(b)
theta = np.arccos(ab_dot / (norm_a * norm_b))
return theta
theta = angle_between_vectors(a,b)
print theta
## create rotation matrix
def rotation_matrix(theta):
""" create a rotation matrix given theta"""
rot = np.array([
[np.cos(theta), -np.sin(theta)],
[np.sin(theta), np.cos(theta)],
])
return rot
ab_rot = rotation_matrix(theta)
print ab_rot
## we know the angle between a and b
## find a vector rotated by the same amount relative to c = [7,8,9],
c = np.array([7,8])
new = c.dot(ab_rot)
print angle_between_vectors(c,new)
## How would you test this?
Much like the basic arithmetic operations we discussed above, comparison operations are perfomed element-wise. That is, rather than returning a
single boolean, comparison operators compare each element in both arrays pairwise, and return an array
of booleans (if the sizes of the input
arrays are incompatible, the comparison will simply return False). For example:
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([1, 1, 3, 3, 5])
print(arr1 == arr2)
c = (arr1 == arr2)
print c.dtype
Note: You can use the methods .any()
and .all()
or the functions np.any
and np.all
to return a single boolean indicating whether any or all values in the array are True
, respectively.
print(np.all(c))
print(c.all())
print(c.any())
In addition to the usual methods of indexing lists with an integer (or with a series of colon-separated integers for a slice), numpy allows you to index arrays in a wide variety of different ways for more advanced operations.
First, the simple way:
Note: python indexes from zero
a = np.array([1,2,3])
print a[0:2]
c = np.random.rand(3,3)
print(c)
print(c[1:3,0:2])
c[0,:] = a
print(c)
We can manipulate the shape of an array as follows:
A = np.arange(16).reshape(4, 4)
Or even:
A = np.reshape(numpy.arange(16), (4, 4))
Using what we've learned about slicing and indexing,
Create A, index the array to get the upper-left quarter
create a function
0
to n**2-1
(like A
)For example, for A, the desired output would be:
array([[2, 3],
[6, 7]])
# create A and slice to get upper corner
A = np.arange(16).reshape(4,4)
print A
print A[:2,2:]
# create code that generates a square array, and outputs upper 4th quarter
n = 12
def generate_array(n):
""" generate a n by n array with vlaues from
0 to n*n """
out = np.reshape(np.arange(0, n**2), (n,n))
fourth = np.round(n / 4.)
return out[:fourth, fourth*3:]
print generate_array(16)
Arrays can be indexed with other arrays, using either an array of indices, or an array of booleans of the same length. In the former case, numpy returns a view of the data in the specified indices as a new array. In the latter, numpy returns a view of the array with only the elements where the index array is True. (We'll discuss the difference between views and copies in a moment.) This makes normally-tedious operations like clamping extremely simple.
Indexing with an array of indices:
A = np.arange(5, 10)
print(A)
print(A[[0, 2, 3]])
A[[0, 2, 3]] = 0
print(A)
Indexing with a boolean array:
random = np.random
A = np.array([random.randint(0, 10) for i in range(10)]) # Check out the list comprehension!
print(A)
A[A>5] = 5
print(A)
A few more examples:
b = np.array([4,5,6])
print (a)
print (b)
print (a > 2)
print (a[a > 2])
print (b[a > 2])
b[a == 3] = 77
print(b)
# There are handy ways to make arrays full of ones and zeros
print(np.zeros(5))
print np.ones(5)
print np.identity(5), '\n'
A = np.arange(5)*2
print(A)
B = range(5)*2
print(B)
Similarly, when adding two numpy arrays together, we get the vector sum back, whereas when adding two lists together, we get the concatenation back.
A = np.arange(5) + np.arange(5)
print(A)
B =range(5) + range(5)
print(B)
In order to be as efficient as possible, numpy uses "views" instead of copies wherever possible. That is, numpy arrays derived from another base array generally refer to the ''exact same data'' as the base array. The consequence of this is that modification of these derived arrays will also modify the base array. The result of an array indexed by an array of indices is a ''copy'', but an array indexed by an array of booleans is a ''view''.
Specifically, slices of arrays are always views, unlike slices of lists or tuples, which are always copies.
A = np.arange(5)
B = A[0:1]
B[0] = 42
print(A)
A = range(5)
B = A[0:1]
B[0] = 42
print(A)
Figure out how to create a copy of a numpy array. Remember: since numpy slices are views, you can't use the trick you'd use for Python lists, i.e. copy = list[:].
## create an array of 10 random numbers
## np.random.random?
myarr = np.random.random((10))
# create a view and change the first element in the view
## what is the value in the original
print 'original first element', myarr[0]
viewarr = myarr[:]
viewarr[0] = 42
print 'view', viewarr[0], 'original', myarr[0]
copyarr = myarr.copy()
## now create a copy
print 'all values equal',np.all(copyarr == myarr)
print 'same object', copyarr is myarr
print 'change copy'
copyarr[0] = 0
print 'copy', copyarr[0], 'orig',myarr[0]
print 'all values equal', np.all(copyarr == myarr)
Being designed for scientific computing, numpy also contains a host of common mathematical functions, including linear algebra functions, fast Fourier transforms, and probability/statistics functions. While there isn't space to go over ''all'' of these in detail, we will provide an overview of the most common/essential of these.
For >2-dimensional arrays, there are some other common matrix operations that can be conducted:
A = np.arange(16).reshape(4, 4)
print(A)
print(A.T) # transpose
print(A.trace())
There are many more methods like these available with NumPy arrays. Be sure to consult the numpy documentation before writing your own versions!
matrix
class¶So far, we've used two-dimensional arrays to represent matrix-like objects. However, numpy provides a specialized class for this. The matrix
class is almost identical to a two-dimensional numpy array, but has a few changes to the interface to simplify common linear algebraic tasks. These are:
* The * operator is performs matrix multiplication
* The ** operator performs matrix exponentiation
* The property .I (or the method .getI()) returns the matrix inverse
* The property .H (or the method .getH()) returns the conjugate transpose
la = np.linalg
A = np.matrix([[3, 2, -1], [2, -2, 4], [-1, .5, -1]])
B = np.array([1, -2, 0])
print(la.solve(A, B))
Universal functions (also called ufuncs) are high-speed, element-wise operations on NumPy arrays. They are, in essence, what allows you to operate on NumPy arrays efficiently. There are a large number of universal functions available covering most of the basic operations that get performed on data, like addition, subtraction, logarithms, and so on. Calling a ufunc is a simple matter:
A = np.arange(1,10)
print(np.log10(A))
In addition to basic operation like above, ufuncs that take two input arrays and return an output array can be used in more advanced ways.
Use %timeit magic to check speed
Using ufuncs, calculate the log of each element in the following array, compare speed to list operation:
[8.1, 1.6, 0.9, 4.3, 7.0, 7.3, 4.7, 8.2, 7.2, 3.0, 1.4, 9.8, 5.7, 0.7, 8.7, 4.6, 8.8, 0.9, 4.4, 4.4]
# create list, and array
## calculate log on all elements in list (list comprehension)
## calculate log on all elements in array
## use timeit to compare processing time
jnk = [8.1, 1.6, 0.9, 4.3, 7.0, 7.3, 4.7, 8.2, 7.2, 3.0, 1.4, 9.8, 5.7, 0.7, 8.7, 4.6, 8.8, 0.9, 4.4, 4.4]
jnk_arr = np.array(jnk)
%timeit [np.log(x) for x in jnk]
%timeit np.log(jnk_arr)