Creating Tables with NumPy
Introduction
Welcome back to Creating and Selecting from 2D NumPy Arrays. We’re now on lesson two, where we’ll create whole tables by describing their shapes instead of typing every value. We’ll use NumPy’s zeros, full, and ones functions to make tables for ticket counts, unassigned seats, and starting weights. As you may recall from the previous lesson, a table’s shape lists its rows first and its columns second. We’ll use that idea to check each table we build.
Why Build Tables Without Typing Every Value
Sometimes we know how large a table should be before we have its actual data. For example, a ticketing system may need space for three screens and four showtimes, even before anyone buys a ticket. NumPy can create all the cells at once with a chosen starting value. This saves us from typing repeated values and makes the table’s intended size clear. We’ll choose a factory function based on the value that should fill the table.
Creating a Table of Zeros with `np.zeros`
Use np.zeros when every cell should start at zero. Its first argument is the table’s shape, written as a tuple in the order (rows, columns). Here, three screens and four showtimes call for a table with three rows and four columns.
The function creates all twelve cells in one call. By default, NumPy uses floating-point numbers, so the zeros are stored as 0., rather than as whole-number 0 values. We’ll change that next, since ticket counts are whole numbers.
Whole Numbers with `dtype=int`
Ticket counts should be whole numbers, so we can pass dtype=int to np.zeros. The dtype argument tells NumPy what kind of values to store. We can print the table and its shape to check both its starting values and its layout.
This creates the same three-row, four-column table but stores its zeros as integers. The output is:
The shape confirms three rows and four columns, matching the screen and showtime layout. Notice that the values have no decimal points.
