Python Lesson 2
Lesson outline
Working with pics.
More about NumPy.
Introduction to data representation with
matplotlib
.Exercises
Working with pics
Import NumPy
as in the previous lesson and pyplot
and image
libraries from matplotlib
.
Read a jpg
figure into an array and show it
Let's examine the array shape
This is an RGB array with three values assigned per pixel. Let's now perform some basic manipulation of this array. We select the three RGB channels, the red, green and blue ones, transforming them to 2D arrays and showing them as heat maps
Change to a color map
More about NumPy
Apart from reading data from files or, as we will see in the next lesson, transforming native Python structures into NumPy ndarrays using np.array
NumPy provides a set of commands for the creation of arrays
ones
: Given array dimensions, it outputs an array with the given shape filled with the value 1.ones_like
: Given an array, it outputs an array with the same dimensions and filled with the value 1.zeros
: Given array dimensions, it outputs an array with the given shape filled with the value 0.zeros_like
: Given an array, it outputs an array with the same dimensions and filled with the value 0.empty
: Given array dimensions, it outputs an array with the same dimensions and with empty values (unitialized, be careful, getting into the wild side…).empty_like
: Given an array, it outputs an array with the same dimensions and with unitialized values.full
: Given array dimensions, it outputs an array with the same dimensions and with all elements equal to a given value.full_like
: Given an array, it outputs an array with the same dimensions and with all elements equal to a given value.eye
,identitiy
: Given a square array dimension, it outputs a unit array (diagonal array) with the given shape.arange
: Given start, stop [and step/] values, creates a 1D ndarray of evenly spaced values with /start as its first element, start + step the second, start + 2 step the third, and so on.linspace
: Given start, stop [and N/] values, creates a 1D ndarray of exactly /N evenly spaced values with start as its first element and stop as the last one.
NumPy offers many types of data, with different dtype
, for its storage in arrays. We are mainly interested in numerical data types, that are indicated by the prefix float (floating point numbers) or int (exact integer numbers) followed by a number indicating the number of bits per element. The standard double-precision floating point value is float64 (requires storage in 8 bytes) and the standard integer is int64. NumPy accepts complex values.
One of the main advantages of NumPy is vectorization, the possibility of performing simultaneously batches of operations in arrays without explicit loops. For example, we define a couple of arrays of random numbers and perform some operations with them
The function np.sqrt
is an example of what is called an universal function (ufunc) that performs element-wise operations in data arrays. You can find a list of such NumPy functions in https://docs.scipy.org/doc/numpy-1.14.0/reference/ufuncs.html. Among them you can find the mathematical constants np.pi
and np.e
and the imaginary unit denoted as 1j
..
One needs to be very aware that when working with NumPy arrays -and other data structures- Python uses the so called pass by reference and not the pass by value strategy of other programming languages. This means that an assignment implies a reference to data in the righthand side. This is completely different of what happens when we work with scalar data. If we execute
Therefore array_b
and array_c
are bound to the same ndarray
object. This is due to the need of optimizing the work with large matrices. A side effect of this is that you cannot assign values to elements of an array that has not been previously created (the function np.zeros
is often used for this purpose). If you want a copy of the original matrix you can either use the copy
method
NumPy also allows to index using integer arrays, something called fancy indexing. In this case the resulting array is copied and it is not a reference to the original array. This can be seen in the following example
NumPy arrays can be transposed using the transpose
method or the special T
attribute
This is useful for example when computing the inner matrix product using np.dot
However, to perform matrix multiplication it is preferred using np.matmul
or the a @ b
notation.
Two or more NumPy arrays can also be concatenated, building up a large array from smaller ones. This can be done with the hstack
and vstack
methods.
Notice that in the hstack~(~vstack
) case the number of rows(columns) in the arrays combined should be the same. These two are convenience functions, wrappers to the more general function concatenate
Data in an array can also be flattened, tranforming the array into a vector (a one-dimensional array). This can be done with the NumPy ravel
or flatten
functions, both can act as a function or an array method.
Note how we check if the two vectors created are equal. The NumPy function np.array_equal
check if two arrays have identical shape and elements. You cannot check if two arrays are equal using the usual ==
conditional operator (try it). Both methods leave arr_c
unchanged, but the ravel
method provides an ndarray
vector with access to the original data, while flatten
copy the data and creates an independent object.
The comparison between arrays yields Boolean arrays
And you can use this Boolean arrays for indexing. In the example that follows we define a new matrix that only has negative non-zero elements, replacing the positive elements by zero.
This is called vectorized computation, one of the greatest advantages of NumPy. We can, for example, select the positive elements of an array If you want to create a new array with the same shape of arr_c
and with 0 in negative elements and 1 in positive elements you can easily do this in vectorized form, without loops (see Lesson 3)
Be aware that Boolean selection will NOT fail if the Boolean array has not the correct shape and this can be error prone. We will learn a better way for doing this in Lesson 5, using the np.where
function.
Working with array you can construct complex conditionals combining simpler expressions with the logical operators &
(and) and |
(or) (the keywords and
and or
do not work in this context. For example
Selecting data with Booleans arrays always creates a copy of the original date, even if the data are unchanged.
Basic Data Plotting
We repeat what we did in the first lesson, reading one of the files with monthly temperatures and stripping the year from the array.
We can plot the array directly as a heat map
Using a different color map
This is of limited utility. Let's compute and plot the mean monthly temperatures
and the average annual temperatures
In the same fashion we can also plot the maximum and minimum monthly temperatures
And the annual maximum and minimum temperatures
This is the most basic plotting in pyplot
. You can improve the figure appearence as follows
You can now solve exercises 2.1 and 2.2
We can combine several plots in a multi-panel figure
You can now solve exercise 2.3.
Exercises
Exercise 2.1: Plot the monthly and annual difference between max and min temperatures as a function of the month (1-12) and the year (1961-2096), respectively. In this case try to combine the
plt.plot
andplt.scatter
functions. Hint: the plot function accept the syntaxplt.plot(x,y)
.Exercise 2.2: Plot the standard deviation of the monthly and annual temperatures as a function of the month (1-12) and the year (1961-2096), respectively. Hint: check the std function in NumPy.
Exercise 2.3: Prepare a plot with two panels (arranged as you wish) which depicts the annual dependence of the average Spring and Fall temperatures for meteorological seasons: Spring (Mar, Apr, May) and Fall (Sep, Oct, Nov).
Last updated
Was this helpful?