The numpy
package (module) is used in almost all numerical computation using Python. It is a package that provide high-performance vector, matrix and higher-dimensional data structures for Python. It is implemented in C and Fortran so when calculations are vectorized (formulated with vectors and matrices), performance is very good.
NumPy
adds basic MATLAB-like capability to Python:
int8
, uint32
, float64
)reshape
, transpose
, concatenate
)ones
, zeros
, eye
, random
)add
, multiply
, max
, sin
)inner
/outer
product, rank
, trace
)inv
, pinv
, svd
, eig
, det
, qr
)SciPy
builds on NumPy
(much like MATLAB toolboxes) adding:
Matplotlib
adds MATLAB-like plotting capability on top of NumPy
.
There are several ways to import numpy
. The standard approach is to use a simple import
statement.
import numpy
However, for large amounts of calls to numpy
functions, it can become tedious to write
numpy.X
over and over again. Instead, it is common to import under the briefer name np
.
import numpy as np
This statement will allow us to access numpy
objects using np.X
instead of numpy.X
. It is
also possible to import numpy
directly into the current namespace so that we don't have to use
dot notation at all, but rather simply call the functions as if they were built-in:
from numpy import *
PyLab is a meta-package that import most of the NumPy
and Matplotlib
into the global name space. It is the easiest (and most MATLAB-like) way to work with scientific Python.
from pylab import *
In Jupyter notebooks we can use %pylab
magic to initiate PyLab evnironment. Option inline
set graphical output to be shown in notebook. For other magic commands see Built-in magic commands. %pylab
makes the following imports.
import numpy
import matplotlib
from matplotlib import pylab, mlab, pyplot
np = numpy
plt = pyplot
from IPython.display import display
from IPython.core.pylabtools import figsize, getfigs
from pylab import *
from numpy import *
%pylab inline
Populating the interactive namespace from numpy and matplotlib
When writing scripts or programs it is recommended that you:
The community has adopted abbreviated naming conventions
import numpy as np
import scipy as sp
import matplotlib as mpl
import matplotlib.pyplot as plt
Some different ways of working with NumPy
are:
from numpy import eye, array # Import only what you need
from numpy.linalg import svd
In the numpy
package the terminology used for vectors, matrices and higher-dimensional data sets is numpy.ndarray
.
The numpy.ndarray
looks awefully much like a Python list (or nested list). Why not simply use Python lists for computations instead of creating a new array type?
There are several reasons:
numpy
arrays can be implemented in a compiled language (C and Fortran is used).There are a number of ways to initialize new numpy arrays, for example from
arange
, linspace
, etc.For example, to create new vector and matrix arrays from Python lists we can use the numpy.array
function.
# a vector: the argument to the array function is a Python list
v = array([1,2,3,8])
v
array([1, 2, 3, 8])
# a matrix: the argument to the array function is a nested Python list
M = array([[1, 2], [3, 4]])
M
array([[1, 2], [3, 4]])
The v
and M
objects are both of the type ndarray
that the numpy
module provides.
type(v), type(M)
(numpy.ndarray, numpy.ndarray)
ndarray
properties¶The difference between the v
and M
arrays is only their shapes. We can get information about the shape of an array by using the ndarray.shape
property.
v.shape
(4,)
M.shape
(2, 2)
The number of elements in the array is available through the ndarray.size
property:
M.size
4
Equivalently, we could use the function numpy.shape
and numpy.size
shape(M)
(2, 2)
size(M)
4
The number of dimensions of the array is available through the ndarray.ndim
property:
v.ndim
1
M.ndim
2
M.itemsize # bytes per element
8
M.nbytes # number of bytes
32
Using the dtype
(data type) property of an ndarray
, we can see what type the data of an array has:
M.dtype
dtype('int64')
We get an error if we try to assign a value of the wrong type to an element in a numpy array:
M[0,0] = "hello"
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-15-e1f336250f69> in <module> ----> 1 M[0,0] = "hello" ValueError: invalid literal for int() with base 10: 'hello'
For larger arrays it is inpractical to initialize the data manually, using explicit python lists. Instead we can use one of the many functions in numpy
that generate arrays of different forms. Some of the more common are:
# create a range
x = arange(0, 10, 1) # arguments: start, stop, step
x
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
x = arange(-1, 1, 0.1)
x
array([-1.00000000e+00, -9.00000000e-01, -8.00000000e-01, -7.00000000e-01, -6.00000000e-01, -5.00000000e-01, -4.00000000e-01, -3.00000000e-01, -2.00000000e-01, -1.00000000e-01, -2.22044605e-16, 1.00000000e-01, 2.00000000e-01, 3.00000000e-01, 4.00000000e-01, 5.00000000e-01, 6.00000000e-01, 7.00000000e-01, 8.00000000e-01, 9.00000000e-01])
# using linspace, both end points ARE included
linspace(0, 10, 21)
array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. , 5.5, 6. , 6.5, 7. , 7.5, 8. , 8.5, 9. , 9.5, 10. ])
logspace(0, 2, 10, base=10)
array([ 1. , 1.66810054, 2.7825594 , 4.64158883, 7.74263683, 12.91549665, 21.5443469 , 35.93813664, 59.94842503, 100. ])
xa = linspace(-5, 5, 11)
ya = linspace(-3, 3, 7)
x, y = meshgrid(xa, ya) # similar to meshgrid in MATLAB
x
array([[-5., -4., -3., -2., -1., 0., 1., 2., 3., 4., 5.], [-5., -4., -3., -2., -1., 0., 1., 2., 3., 4., 5.], [-5., -4., -3., -2., -1., 0., 1., 2., 3., 4., 5.], [-5., -4., -3., -2., -1., 0., 1., 2., 3., 4., 5.], [-5., -4., -3., -2., -1., 0., 1., 2., 3., 4., 5.], [-5., -4., -3., -2., -1., 0., 1., 2., 3., 4., 5.], [-5., -4., -3., -2., -1., 0., 1., 2., 3., 4., 5.]])
y
array([[-3., -3., -3., -3., -3., -3., -3., -3., -3., -3., -3.], [-2., -2., -2., -2., -2., -2., -2., -2., -2., -2., -2.], [-1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [ 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.], [ 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3.]])
# a diagonal matrix
diag([1,2,3])
array([[1, 0, 0], [0, 2, 0], [0, 0, 3]])
# diagonal with offset from the main diagonal
diag([1,2,3], k=1)
array([[0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3], [0, 0, 0, 0]])
zeros((3,3))
array([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]])
ones((3,3))
array([[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]])
identity(3)
array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
zeros_like(x)
array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
ones_like(x)
array([[1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]])
We can index elements in an array using square brackets and indices:
# v is a vector, and has only one dimension, taking one index
v[0]
1
# M is a matrix, or a 2 dimensional array. Index could be chained
M[1][1]
4
# M is a matrix, or a 2 dimensional array, index can take also two indices
M[1,1]
4
If we omit an index of a multidimensional array it returns the whole row (or, in general, a N-1 dimensional array)
M
array([[1, 2], [3, 4]])
M[1]
array([3, 4])
The same thing can be achieved with using :
instead of an index:
M[1,:] # row 1
array([3, 4])
M[:,1] # column 1
array([2, 4])
We can assign new values to elements in an array using indexing:
M[0,0] = -1
M
array([[-1, 2], [ 3, 4]])
# also works for rows and columns
M[0,:] = 0
M[:,1] = -1
M
array([[ 0, -1], [ 3, -1]])
Index slicing is the technical name for the syntax M[lower:upper:step]
to extract part of an array:
A = array([1,2,3,4,5])
A
array([1, 2, 3, 4, 5])
A[1:3]
array([2, 3])
Array slices are mutable: if they are assigned a new value the original array from which the slice was extracted is modified:
A[1:3] = [-2,-3]
A
array([ 1, -2, -3, 4, 5])
We can omit any of the three parameters in M[lower:upper:step]
:
A[::] # lower, upper, step all take the default values
array([ 1, -2, -3, 4, 5])
A[::2] # step is 2, lower and upper defaults to the beginning and end of the array
array([ 1, -3, 5])
A[:3] # first three elements
array([ 1, -2, -3])
A[3:] # elements from index 3
array([4, 5])
Negative indices counts from the end of the array (positive index from the begining):
A = array([1,2,3,4,5])
A[-1] # the last element in the array
5
A[-3:] # the last three elements
array([3, 4, 5])
Index slicing works exactly the same way for multidimensional arrays:
A = array([[n+m*10 for n in range(5)] for m in range(5)]) # note nested list comprehension
A
array([[ 0, 1, 2, 3, 4], [10, 11, 12, 13, 14], [20, 21, 22, 23, 24], [30, 31, 32, 33, 34], [40, 41, 42, 43, 44]])
# a block from the original array
A[1:4, 1:4]
array([[11, 12, 13], [21, 22, 23], [31, 32, 33]])
# strides
A[::2, ::2]
array([[ 0, 2, 4], [20, 22, 24], [40, 42, 44]])
Fancy indexing is the name for when an array or list is used in-place of an index:
row_indices = [1, 2, 3]
A[row_indices]
array([[10, 11, 12, 13, 14], [20, 21, 22, 23, 24], [30, 31, 32, 33, 34]])
col_indices = [1, 2, -1] # remember, index -1 means the last element
A[row_indices, col_indices]
array([11, 22, 34])
We can also use index masks: If the index mask is an Numpy array of data type bool
, then an element is selected (True) or not (False) depending on the value of the index mask at the position of each element:
B = array([n for n in range(5)])
B
array([0, 1, 2, 3, 4])
row_mask = array([True, False, True, False, False])
B[row_mask]
array([0, 2])
# same thing
row_mask = array([1,0,1,0,0], dtype=bool)
B[row_mask]
array([0, 2])
This feature is very useful to conditionally select elements from an array, using for example comparison operators:
x = arange(0, 10, 0.5)
x
array([0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. , 5.5, 6. , 6.5, 7. , 7.5, 8. , 8.5, 9. , 9.5])
Operator | Function | Description |
---|---|---|
& |
bitwise_and(x1, x2) |
Compute the bit-wise AND of two arrays element-wise. |
| |
bitwise_or(x1, x2) |
Compute the bit-wise OR of two arrays element-wise. |
^ |
bitwise_xor(x1, x2) |
Compute the bit-wise XOR of two arrays element-wise. |
~ |
invert(x) |
Compute bit-wise inversion, or bit-wise NOT, element-wise. |
mask = (5 < x) & (x <= 7)
print(mask)
print(x[mask])
[False False False False False False False False False False False True True True True False False False False False] [5.5 6. 6.5 7. ]
mask = (x < 4) | (x > 7)
print(mask)
print(x[mask])
[ True True True True True True True True False False False False False False False True True True True True] [0. 0.5 1. 1.5 2. 2.5 3. 3.5 7.5 8. 8.5 9. 9.5]
Basic mathematical functions operate elementwise on arrays, and are available both as operator overloads and as functions in the numpy
module. Vectorizing code is the key to writing efficient numerical calculation with Python/Numpy. That means that as much as possible of a program should be formulated in terms of matrix and vector operations, like matrix-matrix multiplication.
We can use the usual arithmetic operators to multiply, add, subtract, and divide arrays with scalar numbers.
v1 = arange(0, 5)
v1 * 2
array([0, 2, 4, 6, 8])
v1 + 2
array([2, 3, 4, 5, 6])
A * 2
array([[ 0, 2, 4, 6, 8], [20, 22, 24, 26, 28], [40, 42, 44, 46, 48], [60, 62, 64, 66, 68], [80, 82, 84, 86, 88]])
A + 2
array([[ 2, 3, 4, 5, 6], [12, 13, 14, 15, 16], [22, 23, 24, 25, 26], [32, 33, 34, 35, 36], [42, 43, 44, 45, 46]])
A + A.T
array([[ 0, 11, 22, 33, 44], [11, 22, 33, 44, 55], [22, 33, 44, 55, 66], [33, 44, 55, 66, 77], [44, 55, 66, 77, 88]])
Above we have used the .T to transpose the matrix object v. We could also have used the transpose function to accomplish the same thing.
When we add, subtract, multiply and divide arrays with each other, the default behaviour is element-wise operations:
A * A # element-wise multiplication
array([[ 0, 1, 4, 9, 16], [ 100, 121, 144, 169, 196], [ 400, 441, 484, 529, 576], [ 900, 961, 1024, 1089, 1156], [1600, 1681, 1764, 1849, 1936]])
v1 * v1
array([ 0, 1, 4, 9, 16])
If we multiply arrays with compatible shapes, we get an element-wise multiplication of each row:
A.shape, v1.shape
((5, 5), (5,))
A * v1
array([[ 0, 1, 4, 9, 16], [ 0, 11, 24, 39, 56], [ 0, 21, 44, 69, 96], [ 0, 31, 64, 99, 136], [ 0, 41, 84, 129, 176]])
Numpy provides many useful functions for performing computations on arrays; one of the most useful is sum
print(A)
print('Sum of all elements:', sum(A))
print('Sum of each column: ', sum(A, axis=0))
print('Sum of each row: ', sum(A, axis=1))
[[ 0 1 2 3 4] [10 11 12 13 14] [20 21 22 23 24] [30 31 32 33 34] [40 41 42 43 44]] Sum of all elements: 550 Sum of each column: [100 105 110 115 120] Sum of each row: [ 10 60 110 160 210]
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.
x = array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = array([1, 0, 1])
print(x)
[[ 1 2 3] [ 4 5 6] [ 7 8 9] [10 11 12]]
print(x + v)
[[ 2 2 4] [ 5 5 7] [ 8 8 10] [11 11 13]]
The 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. It is similar for other mathematical operations as well.
print(x * v)
[[ 1 0 3] [ 4 0 6] [ 7 0 9] [10 0 12]]
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.
dot(A, A)
array([[ 300, 310, 320, 330, 340], [1300, 1360, 1420, 1480, 1540], [2300, 2410, 2520, 2630, 2740], [3300, 3460, 3620, 3780, 3940], [4300, 4510, 4720, 4930, 5140]])
dot(A, v1)
array([ 30, 130, 230, 330, 430])
A.dot(v1)
array([ 30, 130, 230, 330, 430])
From Python 3.5 there is new operator '@' for matrix multiplication and numpy has support for it.
A @ v1
array([ 30, 130, 230, 330, 430])
dot(v1,v1), v1.dot(v1), v1 @ v1
(30, 30, 30)
Alternatively, we can cast the array objects to the type matrix
. This changes the behavior of the standard arithmetic operators +, -, *
to use matrix algebra.
M = matrix(A)
v = matrix(v1).T # make it a column vector
v
matrix([[0], [1], [2], [3], [4]])
M * M
matrix([[ 300, 310, 320, 330, 340], [1300, 1360, 1420, 1480, 1540], [2300, 2410, 2520, 2630, 2740], [3300, 3460, 3620, 3780, 3940], [4300, 4510, 4720, 4930, 5140]])
M * v
matrix([[ 30], [130], [230], [330], [430]])
# inner product
v.T * v
matrix([[30]])
# with matrix objects, standard matrix algebra applies
v + M*v
matrix([[ 30], [131], [232], [333], [434]])
If we try to add, subtract or multiply objects with incomplatible shapes we get an error:
v = matrix([1,2,3,4,5,6]).T
shape(M), shape(v)
((5, 5), (6, 1))
M * v
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-90-e8f88679fe45> in <module> ----> 1 M * v ~/miniconda3/lib/python3.7/site-packages/numpy/matrixlib/defmatrix.py in __mul__(self, other) 218 if isinstance(other, (N.ndarray, list, tuple)) : 219 # This promotes 1-D vectors to row vectors --> 220 return N.dot(self, asmatrix(other)) 221 if isscalar(other) or not hasattr(other, '__rmul__') : 222 return N.dot(self, other) <__array_function__ internals> in dot(*args, **kwargs) ValueError: shapes (5,5) and (6,1) not aligned: 5 (dim 1) != 6 (dim 0)
See also the related functions: inner
, outer
, cross
, kron
, tensordot
. Try for example help(kron)
.
M = array([[1, 2], [3, 4]])
inv(M) # equivalent to M.I when M is matrix
--------------------------------------------------------------------------- LinAlgError Traceback (most recent call last) <ipython-input-91-c17ce4a2b5f1> in <module> ----> 1 inv(M) # equivalent to M.I when M is matrix <__array_function__ internals> in inv(*args, **kwargs) ~/miniconda3/lib/python3.7/site-packages/numpy/linalg/linalg.py in inv(a) 549 signature = 'D->D' if isComplexType(t) else 'd->d' 550 extobj = get_linalg_error_extobj(_raise_linalgerror_singular) --> 551 ainv = _umath_linalg.inv(a, signature=signature, extobj=extobj) 552 return wrap(ainv.astype(result_t, copy=False)) 553 ~/miniconda3/lib/python3.7/site-packages/numpy/linalg/linalg.py in _raise_linalgerror_singular(err, flag) 95 96 def _raise_linalgerror_singular(err, flag): ---> 97 raise LinAlgError("Singular matrix") 98 99 def _raise_linalgerror_nonposdef(err, flag): LinAlgError: Singular matrix
dot(inv(M), M)
det(M)
det(inv(M))
Often it is useful to store datasets in Numpy arrays. Numpy provides a number of functions to calculate statistics of datasets in arrays.
d = arange(1, 11)
d
d.mean(), mean(d)
d.std(), d.var(), std(d), var(d)
d.min(), min(d)
d.max(), max(d)
# sum up all elements
d.sum(), sum(d)
# product of all elements
d.prod(), prod(d)
# cummulative sum
d.cumsum(), cumsum(d)
# cummulative product
d. cumprod(), cumprod(d)
A
# same as: diag(A).sum()
trace(A)
When functions such as min
, max
, etc. are applied to a multidimensional arrays, it is sometimes useful to apply the calculation to the entire array, and sometimes only on a row or column basis. Using the axis
argument we can specify how these functions should behave:
M = rand(3,4)
M
# global max
M.max()
# max in each column
M.max(axis=0)
# max in each row
M.max(axis=1)
Many other functions and methods in the array
and matrix
classes accept the same (optional) axis
keyword argument.
The shape of an Numpy array can be modified without copying the underlaying data, which makes it a fast operation even for large arrays.
M
M.shape
N = M.reshape((6, 2))
N
O = M.reshape((1, 12))
O
N[0:2,:] = 1 # modify the array
N
M # and the original variable is also changed. B is only a different view of the same data
O
We can also use the function flatten
to make a higher-dimensional array into a vector. But this function create a copy of the data.
F = M.flatten()
F
F[0:5] = 0
F
M # now M has not changed, because F's data is a copy of M's, not refering to the same data
Using function repeat
, tile
, vstack
, hstack
, and concatenate
we can create larger vectors and matrices from smaller ones:
a = array([[1, 2], [3, 4]])
# repeat each element 3 times
repeat(a, 3)
# tile the matrix 3 times
tile(a, 3)
b = array([[5, 6]])
concatenate((a, b), axis=0)
concatenate((a, b.T), axis=1)
vstack((a,b))
hstack((a,b.T))
System of linear equations like: $$\begin{array}{rcl}x + 2y & = & 5\\3x + 4y & = & 7\end{array}$$
or
$$\begin{pmatrix}1 & 2\\3 & 4\end{pmatrix}\cdot\begin{pmatrix}x \\ y\end{pmatrix} = \begin{pmatrix}5 \\ 7\end{pmatrix}$$could be written in matrix form as $\mathbf {Ax} = \mathbf b$ and could be solved using numpy solve
:
A = array([[1, 2], [3, 4]])
b = array([5,7])
solve(A,b)
or
dot(inv(A),b)
To achieve high performance, assignments in Python usually do not copy the underlaying objects. This is important for example when objects are passed between functions, to avoid an excessive amount of memory copying when it is not necessary (technical term: pass by reference).
# now B is referring to the same array data as A
B = A
# changing B affects A
B[0,0] = 10
B
A
If we want to avoid this behavior, so that when we get a new completely independent object B
copied from A
, then we need to do a so-called "deep copy" using the function copy
:
B = copy(A)
# now, if we modify B, A is not affected
B[0,0] = -5
B
A
Generally, we want to avoid iterating over the elements of arrays whenever we can (at all costs). The reason is that in a interpreted language like Python (or MATLAB), iterations are really slow compared to vectorized operations.
However, sometimes iterations are unavoidable. For such cases, the Python for
loop is the most convenient way to iterate over an array:
v = array([1,2,3,4])
for element in v:
print(element)
M = array([[1,2], [3,4]])
for row in M:
print('Row', row)
for element in row:
print('Element', element)
Row [1 2] Element 1 Element 2 Row [3 4] Element 3 Element 4
When we need to iterate over each element of an array and modify its elements, it is convenient to use the enumerate
function to obtain both the element and its index in the for
loop:
for row_idx, row in enumerate(M):
print("row_idx", row_idx, "row", row)
for col_idx, element in enumerate(row):
print("row_idx", row_idx, "col_idx", col_idx, "Element", element)
# update the matrix M: square each element
M[row_idx, col_idx] = element ** 2
row_idx 0 row [1 2] row_idx 0 col_idx 0 Element 1 row_idx 0 col_idx 1 Element 2 row_idx 1 row [3 4] row_idx 1 col_idx 0 Element 3 row_idx 1 col_idx 1 Element 4
# each element in M is now squared
M
array([[ 1, 4], [ 9, 16]])
When using arrays in conditions,for example if
statements and other boolean expressions, one needs to use any
or all
, which requires that any or all elements in the array evalutes to True
:
M
array([[ 1, 4], [ 9, 16]])
if (M > 5).any():
print("at least one element in M is larger than 5")
else:
print("no element in M is larger than 5")
at least one element in M is larger than 5
if (M > 5).all():
print("all elements in M are larger than 5")
else:
print("all elements in M are not larger than 5")
all elements in M are not larger than 5
For all possibilities check documentation on Input and output.
A very common file format for data files is comma-separated values (CSV), or related formats such as TSV (tab-separated values). To read data from such files into Numpy arrays we can use the numpy.loadtxt
function. For example we will read historical temperature data measured at Prague Clementinum. Here is how file looks like:
!head clementinum.csv
year,month,day,avg,max,min,prec 1972,1,1,0.6,2.8,-0.3,0.0 1972,1,2,1.6,2.5,-1.4,0.0 1972,1,3,3.5,4.0,2.3,0.0 1972,1,4,4.0,4.8,2.9,0.2 1972,1,5,2.2,3.6,1.3,3.0 1972,1,6,0.5,2.3,-1.2,0.0 1972,1,7,1.7,2.3,0.8,0.6 1972,1,8,1.2,1.8,0.0,1.1 1972,1,9,1.7,2.2,0.2,0.0
# read CSV file, skip one row with headings
data = loadtxt('clementinum.csv', skiprows=1, delimiter=',')
data.shape
(16071, 7)
Let's calculate some properties from the Prague temperature dataset used above.
# Prague temperature over the last 43 years
# the average temperature data is in column 3, max in column 4 a min in column 5
print('The daily mean temperature has been {:.2f}°C.'.format(data[:,3].mean()))
print('The highest daily average temperature has been {:.2f}°C.'.format(data[:,3].max()))
print('The highest measured temperature has been {:.2f}°C.'.format(data[:,4].max()))
print('The lowest daily average temperature has been {:.2f}°C.'.format(data[:,3].min()))
print('The lowest measured temperature has been {:.2f}°C.'.format(data[:,5].min()))
The daily mean temperature has been 10.77°C. The highest daily average temperature has been 31.00°C. The highest measured temperature has been 37.80°C. The lowest daily average temperature has been -18.00°C. The lowest measured temperature has been -20.20°C.
!python scripts/footnote.py
Running using Python 3.7.5 (default, Oct 25 2019, 15:51:11) [GCC 7.3.0] Testing Python version-> py3.7 OK Testing numpy... -> numpy OK Testing scipy ... -> scipy OK Testing matplotlib... -> pylab OK Testing sympy -> sympy OK ----------------------------- All the IPython Notebooks in this lecture series are available at: https://github.com/ondrolexa/r-python