LearnWave
Learn it. Master it.

Introduction to NumPy

Statistics and files

Find column-wise statistics of data loaded from a file.

Statistical functions on arrays: max(), min(), sum(), mean() and std() (standard deviation).

  • Without an axis they work on the whole array; with axis=0 they work down each column; with axis=1, along each row.
  • For arrayB = [[3, 6], [4, 2]]: arrayB.max() is 6, arrayB.sum() is 15, arrayB.mean() is 3.75; arrayB.mean(axis=0) is [3.5, 4.0] (column means) and arrayB.sum(axis=1) is [9, 6] (row totals).

Loading arrays from files. Data often comes in CSV (comma separated values) text files; each row must have the same number of values.

  • np.loadtxt(): for example np.loadtxt('data.txt', skiprows=1, delimiter=',', dtype=int). skiprows=1 skips the header row; delimiter tells what separates the values; the default dtype is float.
  • unpack=True transposes the result, so each column comes back as a separate array: rollno, mks1, mks2, mks3 = np.loadtxt(..., unpack=True).
  • np.genfromtxt() can also cope with missing or non-numeric values: they become nan (not a number), or -1 when dtype=int. The filling_values parameter sets your own value, such as filling_values=-999. (It uses skip_header=1 to skip the header.)

Saving arrays: np.savetxt('file.txt', array, delimiter=',', fmt='%i') writes an array to a text file; fmt sets the number format (%i for integers).

Example (new): a file of 30 days' rainfall for 3 towns, loaded as rain = np.loadtxt('rain.csv', skiprows=1, delimiter=','), gives a 30 × 3 array; rain.sum(axis=0) is each town's monthly total, and rain.max(axis=1) is the highest reading among the towns on each day.

axis=0 per column, axis=1 per row.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.