A brief note on NumPy Arrays and Graphs: making arrays, maths on whole arrays, slices and masks, summaries along an axis, line and scatter graphs, bars and histograms, subplots, and speeds from data with np.diff. With a worked example, practice, a program and questions to check yourself.
A brief note on NumPy Arrays and Graphs. Read it before a test. Try each question at the end before you open its answer.
import numpy as np.np.array([1, 2, 3]) makes an array from a list. np.zeros(5), np.ones(5) and np.full(5, 7) make filled arrays.np.arange(0, 10, 2) stops before 10. np.linspace(0, 1, 11) gives 11 numbers and includes both ends.shape, ndim, dtype and len describe an array. One decimal makes the whole array decimals.astype(int) cuts off the decimal part. It does not round.v = 4.9 * t**2.np.sqrt, np.exp and np.sin on arrays. Angles go in radians: np.sin(np.deg2rad(30)).True and False. (a > 5).sum() counts the True values.a[0], a[-1], a[2:5]..copy() for a real copy.a[a > 5]. Join conditions with &, | and ~, each in brackets: a[(a > 2) & (a < 9)].np.where(a > 0, a, 0) chooses at every place. np.clip(a, 0, 100) keeps numbers between two limits.sum, mean, min, max, argmax, np.median, cumsum and np.diff turn many numbers into a few.std() divides by . For a sample, write std(ddof=1).a[1, 2] is row 1, column 2; a[:, 0] is the first column.axis=0 works down the columns and gives one value per column. axis=1 gives one value per row.reshape changes the shape, .T swaps rows and columns, and broadcasting joins a column and a row into a table.plt.plot(x, y) joins the points; x comes first. Name the axes with plt.xlabel and plt.ylabel, with the unit."o-" sets markers and a line. Give each line a label, then call plt.legend().np.linspace with at least 100 points.fig, ax = plt.subplots(2, 1) gives several graphs in one picture. Call ax.plot, ax.set_xlabel and so on.ax.errorbar shows uncertainties, and a log scale turns an exponential into a straight line.| Graph | Use it for |
|---|---|
| line | a change over time |
| scatter | the link between two measurements |
| bar | separate groups |
| histogram | the spread of one measurement |
np.diff(x) / np.diff(t) gives the speeds. There is one fewer, and each belongs to the middle of its gap.Three weather stations record the noon temperature, in °C, on four days. Each row is a station and each column is a day.
temps.mean(axis=1) works along each row, so there is one mean per station: 33.25 °C, 22.5 °C and 28.5 °C.temps.max(axis=0) works down each column, so there is one value per day: 31, 33, 35 and 34 °C.temps > 30 is a table of True and False. .sum() counts the True values: 4 readings, all at the first station. A reading of 30 °C is not above 30 °C.temps[0].argmax() gives the place of the biggest number in row 0, which is 2. Counting from 0, that is the third day.A cup of tea cools in a room at 25 °C. The program works out its temperature every half minute, finds when it falls below 50 °C, and draws the graph.
[1, 2] * 2 repeats the list. Make an array first for maths.np.array([1, 2, 3]) + np.array([1, 2]) stops with ValueError: operands could not be broadcast together with shapes (3,) (2,).and between arrays, or a missing bracket. a[a > 2 and a < 5] stops with ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(). Write a[(a > 2) & (a < 5)].math.sin on an array. It stops with TypeError: only 0-dimensional arrays can be converted to Python scalars. Use np.sin.np.sin. np.sin(30) treats 30 as radians. Use np.deg2rad first.plt.plot stops with ValueError: x and y must have same first dimension.np.arange(2, 20, 3) hold, and which is the last one?scores has 5 rows, one for each student, and 3 columns, one for each test. What shape does scores.mean(axis=0) have, and what does each number mean?b = a[1:4] and then b[0] = 0. Does the array a change?np.diff(x) / np.diff(t) give, and at which times do they belong?Log in to join the discussion.
Loading…