DS Data manipulation, analysis and visualisation in Python
December, 2019© 2016, Joris Van den Bossche and Stijn Van Hoey (mailto:jorisvandenbossche@gmail.com, mailto:stijnvanhoey@gmail.com). Licensed under CC BY 4.0 Creative Commons
This notebook is largely based on material of the Python Scientific Lecture Notes (https://scipy-lectures.github.io/), adapted with some exercises.
In [1]:
%matplotlib inline
NumPy is the fundamental package for scientific computing with Python. It contains among other things:
Also known as array oriented computing. The recommended convention to import numpy is:
In [2]:
import numpy as np
In the numpy
package the terminology used for vectors, matrices and higher-dimensional data sets is array. Let's already load some other modules too.
In [3]:
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('darkgrid')
You like to play boardgames, but you want to better know you're chances of rolling a certain combination with 2 dices:
In [4]:
def mydices(throws):
"""
Function to create the distrrbution of the sum of two dices.
Parameters
----------
throws : int
Number of throws with the dices
"""
stone1 = np.random.uniform(1, 6, throws)
stone2 = np.random.uniform(1, 6, throws)
total = stone1 + stone2
return plt.hist(total, bins=20) # We use matplotlib to show a histogram
In [5]:
mydices(100) # test this out with multiple options
Out[5]:
Consider a random 10x2 matrix representing cartesian coordinates, how to convert them to polar coordinates
In [6]:
# random numbers (X, Y in 2 columns)
Z = np.random.random((10,2))
X, Y = Z[:,0], Z[:,1]
# distance
R = np.sqrt(X**2 + Y**2)
# angle
T = np.arctan2(Y, X) # Array of angles in radians
Tdegree = T*180/(np.pi) # If you like degrees more
# NEXT PART (now for illustration)
#plot the cartesian coordinates
plt.figure(figsize=(14, 6))
ax1 = plt.subplot(121)
ax1.plot(Z[:,0], Z[:,1], 'o')
ax1.set_title("Cartesian")
#plot the polar coorsidnates
ax2 = plt.subplot(122, polar=True)
ax2.plot(T, R, 'o')
ax2.set_title("Polar")
Out[6]:
Memory-efficient container that provides fast numerical operations:
In [7]:
L = range(1000)
%timeit [i**2 for i in L]
In [8]:
a = np.arange(1000)
%timeit a**2
In [9]:
#More information about array?
np.array?
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.
In [10]:
# a vector: the argument to the array function is a Python list
V = np.array([1, 2, 3, 4])
V
Out[10]:
In [11]:
# a matrix: the argument to the array function is a nested Python list
M = np.array([[1, 2], [3, 4]])
M
Out[11]:
The v
and M
objects are both of the type ndarray
that the numpy
module provides.
In [12]:
type(V), type(M)
Out[12]:
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.
In [13]:
V.shape
Out[13]:
In [14]:
M.shape
Out[14]:
The number of elements in the array is available through the ndarray.size
property:
In [15]:
M.size
Out[15]:
Equivalently, we could use the function numpy.shape
and numpy.size
In [16]:
np.shape(M)
Out[16]:
In [17]:
np.size(M)
Out[17]:
Using the dtype
(data type) property of an ndarray
, we can see what type the data of an array has (always fixed for each array, cfr. Matlab):
In [18]:
M.dtype
Out[18]:
We get an error if we try to assign a value of the wrong type to an element in a numpy array:
In [19]:
#M[0,0] = "hello" #uncomment this cell
In [20]:
f = np.array(['Bonjour', 'Hello', 'Hallo',])
f
Out[20]:
If we want, we can explicitly define the type of the array data when we create it, using the dtype
keyword argument:
In [21]:
M = np.array([[1, 2], [3, 4]], dtype=complex) #np.float64, np.float, np.int64
print(M, '\n', M.dtype)
Since Numpy arrays are statically typed, the type of an array does not change once created. But we can explicitly cast an array of some type to another using the astype
functions (see also the similar asarray
function). This always create a new array of new type:
In [22]:
M = np.array([[1, 2], [3, 4]], dtype=float)
M2 = M.astype(int)
M2
Out[22]:
Common type that can be used with dtype
are: int
, float
, complex
, bool
, object
, etc.
We can also explicitly define the bit size of the data types, for example: int64
, int16
, float64
, float128
, complex128
.
Higher order is also possible:
In [23]:
C = np.array([[[1], [2]], [[3], [4]]])
print(C.shape)
C
Out[23]:
In [24]:
C.ndim # number of dimensions
Out[24]:
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 generates arrays of different forms. Some of the more common are:
In [25]:
# create a range
x = np.arange(0, 10, 1) # arguments: start, stop, step
x
Out[25]:
In [26]:
x = np.arange(-1, 1, 0.1)
x
Out[26]:
In [27]:
# using linspace, both end points ARE included
np.linspace(0, 10, 25)
Out[27]:
In [28]:
np.logspace(0, 10, 10, base=np.e)
Out[28]:
In [29]:
plt.plot(np.logspace(0, 10, 10, base=np.e), np.random.random(10), 'o')
plt.xscale('log')
In [30]:
# uniform random numbers in [0,1]
np.random.rand(5,5)
Out[30]:
In [31]:
# standard normal distributed random numbers
np.random.randn(5,5)
Out[31]:
In [32]:
np.zeros((3,3))
Out[32]:
In [33]:
np.ones((3,3))
Out[33]:
In [34]:
np.arange(10, 50, 1)
Out[34]:
In [35]:
np.identity(3)
Out[35]:
In [36]:
np.eye(3)
Out[36]:
In [37]:
np.random.random((3, 3, 3))
Out[37]:
Numpy is capable of reading and writing text and binary formats. However, since most data-sources are providing information in a format with headings, different dtypes,... we will use for reading/writing of textfiles the power of Pandas.
Writing to a csvfile with numpy is done with the savetxt-command:
In [38]:
a = np.random.random(40).reshape((20, 2))
np.savetxt("random-matrix.csv", a, delimiter=",")
To read data from such file into Numpy arrays we can use the numpy.genfromtxt
function. For example,
In [39]:
a2 = np.genfromtxt("random-matrix.csv", delimiter=',')
a2
Out[39]:
Useful when storing and reading back numpy array data, since binary. Use the functions numpy.save
and numpy.load
:
In [40]:
np.save("random-matrix.npy", a)
!file random-matrix.npy
In [41]:
np.load("random-matrix.npy")
Out[41]:
We can index elements in an array using the square bracket and indices:
In [42]:
V
Out[42]:
In [43]:
# V is a vector, and has only one dimension, taking one index
V[0]
Out[43]:
In [44]:
V[-1:] #-2, -2:,...
Out[44]:
In [45]:
# a is a matrix, or a 2 dimensional array, taking two indices
# the first dimension corresponds to rows, the second to columns.
a[1, 1]
Out[45]:
If we omit an index of a multidimensional array it returns the whole row (or, in general, a N-1 dimensional array)
In [46]:
a[1]
Out[46]:
The same thing can be achieved with using :
instead of an index:
In [47]:
a[1, :] # row 1
Out[47]:
In [48]:
a[:, 1] # column 1
Out[48]:
We can assign new values to elements in an array using indexing:
In [49]:
a[0, 0] = 1
a[:, 1] = -1
a
Out[49]:
Index slicing is the technical name for the syntax M[lower:upper:step]
to extract part of an array:
In [50]:
A = np.array([1, 2, 3, 4, 5])
A
Out[50]:
In [51]:
A[1:3]
Out[51]:
Array slices are mutable: if they are assigned a new value the original array from which the slice was extracted is modified:
In [52]:
A[1:3] = [-2,-3]
A
Out[52]:
We can omit any of the three parameters in M[lower:upper:step]
:
In [53]:
A[::] # lower, upper, step all take the default values
Out[53]:
In [54]:
A[::2] # step is 2, lower and upper defaults to the beginning and end of the array
Out[54]:
In [55]:
A[:3] # first three elements
Out[55]:
In [56]:
A[3:] # elements from index 3
Out[56]:
In [57]:
A[-3:] # the last three elements
Out[57]:
In [58]:
vec = np.zeros(10)
vec[4] = 1.
vec
Out[58]:
Fancy indexing is the name for when an array or list is used in-place of an index:
In [59]:
a = np.arange(0, 100, 10)
a[[2, 3, 2, 4, 2]]
Out[59]:
In more dimensions:
In [60]:
A = np.arange(25).reshape(5,5)
A
Out[60]:
In [61]:
row_indices = [1, 2, 3]
A[row_indices]
Out[61]:
In [62]:
col_indices = [1, 2, -1] # remember, index -1 means the last element
A[row_indices, col_indices]
Out[62]:
We can also index masks: If the index mask is an Numpy array of with data type bool
, then an element is selected (True) or not (False) depending on the value of the index mask at the position each element:
In [63]:
B = np.array([n for n in range(5)]) #range is pure python => Exercise: Make this shorter with pur numpy
B
Out[63]:
In [64]:
row_mask = np.array([True, False, True, False, False])
B[row_mask]
Out[64]:
In [65]:
# same thing
row_mask = np.array([1,0,1,0,0], dtype=bool)
B[row_mask]
Out[65]:
This feature is very useful to conditionally select elements from an array, using for example comparison operators:
In [66]:
AR = np.random.randint(0, 20, 15)
AR
Out[66]:
In [67]:
AR%3 == 0
Out[67]:
In [68]:
extract_from_AR = AR[AR%3 == 0]
extract_from_AR
Out[68]:
In [69]:
x = np.arange(0, 10, 0.5)
x
Out[69]:
In [70]:
mask = (5 < x) * (x < 7.5) # We actually multiply two masks here (boolean 0 and 1 values)
mask
Out[70]:
In [71]:
x[mask]
Out[71]:
In [72]:
A = np.arange(25).reshape(5,5)
A
Out[72]:
In [73]:
#SWAP
A[[0, 1]] = A[[1, 0]]
A
Out[73]:
In [74]:
AR = np.random.randint(0, 20, 15)
AR
Out[74]:
In [75]:
AR[AR%2==0] = 0.
AR
Out[75]:
In [76]:
AR = np.random.randint(1, 20, 15)
AR
Out[76]:
In [77]:
AR[1::2] = 0
AR
Out[77]:
where function to know the indices of something
In [78]:
x = np.arange(0, 10, 0.5)
np.where(x>5.)
Out[78]:
With the diag function we can also extract the diagonal and subdiagonals of an array:
In [79]:
np.diag(A)
Out[79]:
The take
function is similar to fancy indexing described above:
In [80]:
x.take([1, 5])
Out[80]:
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.
We can use the usual arithmetic operators to multiply, add, subtract, and divide arrays with scalar numbers.
In [81]:
v1 = np.arange(0, 5)
In [82]:
v1 * 2
Out[82]:
In [83]:
v1 + 2
Out[83]:
In [84]:
A = np.arange(25).reshape(5,5)
A * 2
Out[84]:
In [85]:
np.sin(A) #np.log(A), np.arctan,...
Out[85]:
When we add, subtract, multiply and divide arrays with each other, the default behaviour is element-wise operations:
In [86]:
A * A # element-wise multiplication
Out[86]:
In [87]:
v1 * v1
Out[87]:
If we multiply arrays with compatible shapes, we get an element-wise multiplication of each row:
In [88]:
A.shape, v1.shape
Out[88]:
In [89]:
A * v1
Out[89]:
Consider the speed difference with pure python:
In [90]:
a = np.arange(10000)
%timeit a + 1
l = range(10000)
%timeit [i+1 for i in l]
In [91]:
#logical operators:
a1 = np.arange(0, 5, 1)
a2 = np.arange(5, 0, -1)
a1>a2 # >, <=,...
Out[91]:
In [92]:
# cfr.
np.all(a1>a2) # any
Out[92]:
Basic operations on numpy arrays (addition, etc.) are elementwise. Nevertheless, It’s also possible to do operations on arrays of different sizes if Numpy can transform these arrays so that they all have the same size: this conversion is called broadcasting.
In [93]:
A, v1
Out[93]:
In [94]:
A*v1
Out[94]:
In [95]:
x, y = np.arange(5), np.arange(5).reshape((5, 1)) # a row and a column array
In [96]:
distance = np.sqrt(x ** 2 + y ** 2)
distance
Out[96]:
In [97]:
#let's put this in a figure:
plt.pcolor(distance)
plt.colorbar()
Out[97]:
What about matrix mutiplication? There are two ways. We can either use the dot
function, which applies a matrix-matrix, matrix-vector, or inner vector multiplication to its two arguments:
In [98]:
np.dot(A, A)
Out[98]:
In [99]:
np.dot(A, v1) #check the difference with A*v1 !!
Out[99]:
In [100]:
np.dot(v1, v1)
Out[100]:
Alternatively, we can cast the array objects to the type matrix
. This changes the behavior of the standard arithmetic operators +, -, *
to use matrix algebra. You can also get inverse
of matrices, determinant
,...
We won't go deeper here on pure matrix calculation, but for more information, check the related functions: inner
, outer
, cross
, kron
, tensordot
. Try for example help(kron)
.
Often it is useful to store datasets in Numpy arrays. Numpy provides a number of functions to calculate statistics of datasets in arrays.
In [101]:
a = np.random.random(40)
Different frequently used operations can be done:
In [102]:
print ('Mean value is', np.mean(a))
print ('Median value is', np.median(a))
print ('Std is', np.std(a))
print ('Variance is', np.var(a))
print ('Min is', a.min())
print ('Element of minimum value is', a.argmin())
print ('Max is', a.max())
print ('Sum is', np.sum(a))
print ('Prod', np.prod(a))
print ('Cumsum is', np.cumsum(a)[-1])
print ('CumProd of 5 first elements is', np.cumprod(a)[4])
print ('Unique values in this array are:', np.unique(np.random.randint(1,6,10)))
print ('85% Percentile value is: ', np.percentile(a, 85))
In [103]:
a = np.random.random(40)
print(a.argsort())
a.sort() #sorts in place!
print(a.argsort())
When functions such as min
, max
, etc., is 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:
In [104]:
m = np.random.rand(3,3)
m
Out[104]:
In [105]:
# global max
m.max()
Out[105]:
In [106]:
# max in each column
m.max(axis=0)
Out[106]:
In [107]:
# max in each row
m.max(axis=1)
Out[107]:
Many other functions and methods in the array
and matrix
classes accept the same (optional) axis
keyword argument.
In [108]:
Z = np.random.uniform(5.0, 15.0, (5,5))
Z
Out[108]:
In [109]:
# RESCALE:
(Z - Z.min())/(Z.max() - Z.min())
Out[109]:
The shape of an Numpy array can be modified without copying the underlaying data, which makes it a fast operation even for large arrays.
In [110]:
A = np.arange(25).reshape(5,5)
n, m = A.shape
B = A.reshape((1,n*m))
B
Out[110]:
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 (see next)
In [111]:
B = A.flatten()
B
Out[111]:
Using function repeat
, tile
, vstack
, hstack
, and concatenate
we can create larger vectors and matrices from smaller ones:
In [112]:
a = np.array([[1, 2], [3, 4]])
In [113]:
# repeat each element 3 times
np.repeat(a, 3)
Out[113]:
In [114]:
# tile the matrix 3 times
np.tile(a, 3)
Out[114]:
In [115]:
b = np.array([[5, 6]])
In [116]:
np.concatenate((a, b), axis=0)
Out[116]:
In [117]:
np.concatenate((a, b.T), axis=1)
Out[117]:
In [118]:
np.vstack((a,b))
Out[118]:
In [119]:
np.hstack((a,b.T))
Out[119]:
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 (techincal term: pass by reference).
In [120]:
A = np.array([[1, 2], [3, 4]])
A
Out[120]:
In [121]:
# now B is referring to the same array data as A
B = A
In [122]:
# changing B affects A
B[0,0] = 10
B
Out[122]:
In [123]:
A
Out[123]:
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
:
In [124]:
B = np.copy(A)
In [125]:
# now, if we modify B, A is not affected
B[0,0] = -5
B
Out[125]:
In [126]:
A
Out[126]:
Also reshape function just takes a view:
In [127]:
arr = np.arange(8)
arr_view = arr.reshape(2, 4)
In [128]:
print('Before\n', arr_view)
arr[0] = 1000
print('After\n', arr_view)
In [129]:
arr.flatten()[2] = 10 #Flatten creates a copy!
In [130]:
arr
Out[130]:
When using arrays in conditions in for example if
statements and other boolean expressions, one need to use one of any
or all
, which requires that any or all elements in the array evalutes to True
:
In [131]:
M
Out[131]:
In [132]:
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")
In [133]:
if (M > 5).all():
print("all elements in M are larger than 5")
else:
print("all elements in M are not larger than 5")
In [134]:
b_data = np.genfromtxt("./data/bogota_part_dataset.csv", skip_header=3, delimiter=',')
plt.scatter(b_data[:,2], b_data[:,3])
Out[134]:
In [135]:
x, y = b_data[:,1], b_data[:,3]
t = np.polyfit(x, y, 2) # fit a 2nd degree polynomial to the data, result is x**2 + 2x + 3
t
Out[135]:
In [136]:
x.sort()
plt.plot(x, y, 'o')
plt.plot(x, t[0]*x**2 + t[1]*x + t[2], '-')
Out[136]:
In [137]:
x, y = b_data[:,3], b_data[:,4]
t = np.polyfit(x, y, 4) # fit a 2nd degree polynomial to the data, result is x**2 + 2x + 3
t
x.sort()
plt.plot(x, y, 'o')
plt.plot(x, t[0]*x**4 + t[1]*x**3 + t[2]*x**2 + t[3]*x +t[4], '-')
Out[137]:
However, when doing some kind of regression, we would like to have more information about the fit characterstics automatically. Statsmodels is a library that provides this functionality, we will later come back to this type of regression problem.
In [138]:
def moving_average(a, n=3) :
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
In [139]:
print(moving_average(b_data , n=3))
However, the latter fuction implementation is something we would expect from a good data-analysis library to be implemented already.
The perfect timing for Python Pandas!
Know how to create arrays : array, arange, ones, zeros,....
Know the shape of the array with array.shape, then use slicing to obtain different views of the array: array[::2], etc. Adjust the shape of the array using reshape or flatten it.
Obtain a subset of the elements of an array and/or modify their values with masks
Know miscellaneous operations on arrays, such as finding the mean or max (array.max(), array.mean()). No need to retain everything, but have the reflex to search in the documentation (online docs, help(), lookfor())!!
For advanced use: master the indexing with arrays of integers, as well as broadcasting. Know more Numpy functions to handle various array operations.