2.2 Reading and Manipulating Tabular Data

Questions we’ll cover

  • What are libraries?
  • How do I use functions from libraries?
  • How do I define a path to a data file relative to my code file?
  • How can I read, manipulate, and analyze tabular data files in Python?


Words are useful, but what’s more useful are the sentences and stories we build with them. Similarly, while a lot of powerful, general tools are built into Python, specialized tools built up from these basic units live in libraries that can be called upon when needed.

Loading data into Python

To begin processing the book-search data, we need to load it into Python. We can do that using a library called NumPy, which stands for Numerical Python. In general, you should use this library when you want to do fancy things with lots of numbers, especially if you have matrices or arrays. To tell Python that we’d like to start using NumPy, we need to import it:

import numpy

Importing a library is like getting a piece of lab equipment out of a storage locker and setting it up on the bench. Libraries provide additional functionality to the basic Python package, much like a new piece of equipment adds functionality to a lab space. Just like in the lab, importing too many libraries can sometimes complicate and slow down your programs - so we only import what we need for each program.

Once we’ve imported the library, we can ask the library to read our data file for us:

data = numpy.loadtxt(fname="2026-02-18_google-trends-search-1_VALUES.csv", delimiter=',')

These data correspond to the amount of Google searches for 8 different books, over 5 years across Canada. The rows are the individual books, and the columns are months. Note that the values are not the number of searches, but the amount relative to the maximum of the item with the most searches in any month.

The expression numpy.loadtxt(...) is a function call that asks Python to run the function loadtxt which belongs to the numpy library. The dot notation in Python is used most of all as an object attribute/property specifier or for invoking its method. object.property will give you the object.property value, object_name.method() will invoke on object_name method.

As an example, John Smith is the John that belongs to the Smith family. We could use the dot notation to write his name smith.john, just as loadtxt is a function that belongs to the numpy library.

numpy.loadtxt has two parameters: the name of the file we want to read and the delimiter that separates values on a line. These both need to be character strings (or strings for short), so we put them in quotes.

This statement doesn’t produce any output because we’ve assigned the output to the variable data. If we want to check that the data have been loaded, we can print the variable’s value:

print(data)

Note that, to save space when displaying NumPy arrays, Python does not show us trailing zeros, so 1.0 becomes 1..

Now that the data are in memory, we can manipulate them. First, let’s ask what type of thing data refers to:

print(type(data))
<class 'numpy.ndarray'>

The output tells us that data currently refers to an N-dimensional array, the functionality for which is provided by the NumPy library.

Data type within the Numpy array

A Numpy array contains one or more elements of the same type. The type function will only tell you that a variable is a NumPy array but won’t tell you the type of thing inside the array. We can find out the type of the data contained in the NumPy array.

print(data.dtype)
float64

This tells us that the NumPy array’s elements are floating-point numbers.

With the following command, we can see the array’s shape:

print(data.shape)
(8, 61)

The output tells us that the data array variable contains 8 rows and 61 columns. When we created the variable data to store our book-search data, we did not only create the array; we also created information about the array, called members or attributes. This extra information describes data in the same way an adjective describes a noun. data.shape is an attribute of data which describes the dimensions of data. We use the same dotted notation for the attributes of variables that we use for the functions in libraries because they have the same part-and-whole relationship.

If we want to get a single number from the array, we must provide an index in square brackets after the variable name, just as we do in math when referring to an element of a matrix. Our book-search data has two dimensions, so we will need to use two indices to refer to one specific value:

print('first value in data:', data[0, 0])
first value in data: 2.56
print("middle value in data:", data[4, 30])
middle value in data: 0.0

The expression data[4, 30] accesses the element at row 4, column 30. While this expression may not surprise you, data[0, 0] might. Programming languages like Fortran, MATLAB and R start counting at 1 because that’s what human beings have done for thousands of years. Languages in the C family (including C++, Java, Perl, and Python) count from 0 because it represents an offset from the first value in the array (the second value is offset by one index from the first value). This is closer to the way that computers represent arrays (if you are interested in the historical reasons behind counting indices from zero, you can read Mike Hoye’s blog post). As a result, if we have an M×N array in Python, its indices go from 0 to M-1 on the first axis and 0 to N-1 on the second. It takes a bit of getting used to, but one way to remember the rule is that the index is how many steps we have to take from the start to get the item we want.

"'data' is a 3 by 3 numpy array containing row 0: ['A', 'B', 'C'], row 1: ['D', 'E', 'F'], androw 2: ['G', 'H', 'I']. Starting in the upper left hand corner, data[0, 0] = 'A', data[0, 1] = 'B',data[0, 2] = 'C', data[1, 0] = 'D', data[1, 1] = 'E', data[1, 2] = 'F', data[2, 0] = 'G',data[2, 1] = 'H', and data[2, 2] = 'I', in the bottom right hand corner."

In the Corner

What may also surprise you is that when Python displays an array, it shows the element with index [0, 0] in the upper left corner rather than the lower left. This is consistent with the way mathematicians draw matrices but different from the Cartesian coordinates. The indices are (row, column) instead of (column, row) for the same reason, which can be confusing when plotting data.

Slicing data

An index like [4, 30] selects a single element of an array, but we can select whole sections as well. For example, we can select the first ten months (columns) of values for the first four books (rows) like this:

print(data[0:4, 0:10])
[[ 2.56  2.88  2.08 16.    8.8   4.    3.04  0.    2.24  2.08]
 [ 0.    0.    0.    0.    0.    0.    0.    0.    0.    0.  ]
 [ 0.    0.    0.    0.    2.08  0.    0.    0.    0.    0.  ]
 [ 0.    0.    0.    0.    0.    0.    0.    0.    2.24  2.56]]

The slice 0:4 means, “Start at index 0 and go up to, but not including, index 4”. Again, the up-to-but-not-including takes a bit of getting used to, but the rule is that the difference between the upper and lower bounds is the number of values in the slice.

We don’t have to start slices at 0:

print(data[5:10, 0:10])
[[0.   0.   0.   4.48 0.   0.   0.   0.   0.   0.   0.   3.36]
 [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.   1.76 2.88 1.92 1.92 0.  ]]

We also don’t have to include the upper and lower bound on the slice. If we don’t include the lower bound, Python uses 0 by default; if we don’t include the upper, the slice runs to the end of the axis, and if we don’t include either (i.e., if we use ‘:’ on its own), the slice includes everything:

small = data[:3, 58:]
print('small is:')
print(small)

The above example selects rows 0 through 2 and columns 58 through to the end of the array.

small is:
[[0.   0.   0.64]
 [0.   0.   0.32]
 [0.   0.   0.32]]

Analyzing data

NumPy has several useful functions that take an array as input to perform operations on its values. If we want to find the average searches for all books on all months, for example, we can ask NumPy to compute data’s mean value:

print(numpy.mean(data))
mean: 0.878688524590164

mean is a function that takes an array as an argument.

Sidenote: Not All Functions Have Input

Generally, a function uses inputs to produce outputs. However, some functions produce outputs without needing any input. For example, checking the current time doesn’t require any input.

import time
print(time.ctime())
Wed Feb 18 16:55:39 2026

For functions that don’t take in any arguments, we still need parentheses (()) to tell Python to go and do something for us.


Let’s use three other NumPy functions to get some descriptive values about the dataset. We’ll also use multiple assignment, a convenient Python feature that will enable us to do this all in one line.

maxval, minval, stdval = numpy.amax(data), numpy.amin(data), numpy.std(data)

print('maximum searches:', maxval)
print('minimum searches:', minval)
print('standard deviation:', stdval)

Here we’ve assigned the return value from numpy.amax(data) to the variable maxval, the value from numpy.amin(data) to minval, and so on.

maximum searches: 16.0
minimum searches: 0.0
standard deviation: 2.1771266034030643

Sidenote: Mystery Functions in IPython

How did we know what functions NumPy has and how to use them? If you are working in IPython, a Jupyter Notebook, and some text editors, there is an easy way to find out. If you type the name of something followed by a dot, then you can use tab-completion (e.g. type numpy. and then press Tab) to see a list of all functions and attributes that you can use.

Sidenote: Confusing Function Names

s One might wonder why the functions are called amax and amin and not max and min or why the other is called mean and not amean. The package numpy does provide functions max and min that are fully equivalent to amax and amin, but they share a name with standard library functions max and min that come with Python itself. Referring to the functions like we did above, that is numpy.max for example, does not cause problems, but there are other ways to refer to them that could. In addition, text editors might highlight (color) these functions like standard library function, even though they belong to NumPy, which can be confusing and lead to errors. Since there is no function called mean in the standard library, there is no function called amean.


When analyzing data, though, we often want to look at variations in statistical values, such as the maximum searches per book or the average searches per month. One way to do this is to create a new temporary array of the data we want, then ask it to do the calculation:

book_0 = data[0, :] # 0 on the first axis (rows), everything on the second (columns)
print('maximum searches for book 0:', numpy.amax(book_0))
maximum searches for book 0: 16.0

We don’t actually need to store the row in a variable of its own. Instead, we can combine the selection and the function call:

print("maximum searches for book 2:", numpy.amax(data[2, :]))
maximum searches for book 2: 15.84

What if we need the maximum searches for each book over all months (as in the next diagram on the left) or the average for each month (as in the diagram on the right)? As the diagram below shows, we want to perform the operation across an axis:

"Per-book maximum searches is computed row-wise across all columns usingnumpy.amax(data, axis=1). Per-month average searches is computed column-wise across all rows usingnumpy.mean(data, axis=0).

To find the maximum amount of searches reported for each book, you would apply the max function moving across the columns (axis 1). To find the daily average amount of searches reported across books, you would apply the mean function moving down the rows (axis 0).

To support this functionality, most array functions allow us to specify the axis we want to work on. If we ask for the max across axis 1 (columns in our 2D example), we get:

print(numpy.max(data, axis=1))
[16.    3.04 15.84 13.6   4.48  0.32  0.    4.  ]

As a quick check, we can ask this array what its shape is. We expect 8 book maximums because there are 8 books:

print(numpy.max(data, axis=1).shape)
(8,)

The expression (8,) tells us we have an 8×1 vector, so this is the maximum searches per month for each book.

If we ask for the average across/down axis 0 (rows in our 2D example), we get:

print(numpy.mean(data, axis=0))
[0.32 0.36 0.26 2.   1.36 0.5  0.38 0.   0.56 0.58 0.22 0.26 0.6  1.04
 0.52 1.8  1.12 0.76 1.18 2.5  1.38 0.86 0.76 1.46 1.52 1.7  1.78 4.34
 2.46 1.8  0.84 2.9  1.62 0.8  0.8  0.24 0.64 0.72 0.66 0.58 0.52 0.
 0.   0.76 0.3  0.28 0.   0.48 0.24 0.42 0.2  1.62 0.64 0.9  0.42 1.7
 0.28 0.   0.   0.24 0.42]

Check the array shape. We expect 61 averages, one for each month of the study:

print(numpy.mean(data, axis=0).shape)
(61,)

Similarly, we can apply the mean function to axis 1 to get the book’s average searches over the duration of the book (8 values).

print(numpy.mean(data, axis=1))
[1.38229508 0.21245902 1.06491803 3.71672131 0.24393443 0.0052459
 0.         0.40393443]

Challenge: Slicing Strings

A section of an array is called a slice. We can take slices of character strings as well:

element = 'oxygen'
print('first three characters:', element[0:3])
print('last three characters:', element[3:6])
first three characters: oxy
last three characters: gen

Ask yourself: What is the value of element[:4]? What about element[4:]? Or element[:]?

Solution

oxyg
en
oxygen

Ask yourself: What is element[-1]? What is element[-2]?

Solution

n
e

Ask yourself: Given those answers, explain what element[1:-1] does

Solution

Creates a substring from index 1 up to (not including) the final index, effectively removing the first and last letters from ‘oxygen’

Ask yourself: How can we rewrite the slice for getting the last three characters of element,so that it works even if we assign a different string to element?

Test your solution with the following strings: carpentry, clone, hi.

Solution

element = 'oxygen'
print('last three characters:', element[-3:])
element = 'carpentry'
print('last three characters:', element[-3:])
element = 'clone'
print('last three characters:', element[-3:])
element = 'hi'
print('last three characters:', element[-3:])
last three characters: gen
last three characters: try
last three characters: one
last three characters: hi

Challenge: Stacking Arrays

Arrays can be concatenated and stacked on top of one another, using NumPy’s vstack and hstack functions for vertical and horizontal stacking, respectively.

import numpy

A = numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print('A = ')
print(A)

B = numpy.hstack([A, A])
print('B = ')
print(B)

C = numpy.vstack([A, A])
print('C = ')
print(C)
A =
[[1 2 3]
 [4 5 6]
 [7 8 9]]
B =
[[1 2 3 1 2 3]
 [4 5 6 4 5 6]
 [7 8 9 7 8 9]]
C =
[[1 2 3]
 [4 5 6]
 [7 8 9]
 [1 2 3]
 [4 5 6]
 [7 8 9]]

Write some additional code that slices the first and last columns of A, and stacks them into a 3x2 array. Make sure to print the results to verify your solution.

Solution

A ‘gotcha’ with array indexing is that singleton dimensions are dropped by default. That means A[:, 0] is a one dimensional array, which won’t stack as desired. To preserve singleton dimensions, the index itself can be a slice or array. For example, A[:, :1] returns a two dimensional array with one singleton dimension (i.e. a column vector).

D = numpy.hstack((A[:, :1], A[:, -1:]))
print('D = ')
print(D)
D =
[[1 3]
 [4 6]
 [7 9]]

Solution

An alternative way to achieve the same result is to use Numpy’s delete function to remove the second column of A. If you’re not sure what the parameters of numpy.delete mean, use the help files.

D = numpy.delete(arr=A, obj=1, axis=1)
print('D = ')
print(D)
D =
[[1 3]
 [4 6]
 [7 9]]

Key Points

  • Import a library into a program using import libraryname.
  • Use the numpy library to work with arrays in Python.
  • The expression array.shape gives the shape of an array.
  • Use array[x, y] to select a single element from a 2D array.
  • Array indices start at 0, not 1.
  • Use low:high to specify a slice that includes the indices from low to high-1.
  • Use # some kind of explanation to add comments to programs.
  • Use numpy.mean(array), numpy.amax(array), and numpy.amin(array) to calculate simple statistics.
  • Use numpy.mean(array, axis=0) or numpy.mean(array, axis=1) to calculate statistics across the specified axis.

View in GitHub

Loading last updated date...