Start learning free

LESSON 5 OF 165 · MACHINE LEARNING: NUMPY

Rows, Columns and axis in Python

Practice

A 2-D array is a table of numbers. Its .shape gives back the length of each axis: axis 0 runs down the rows and axis 1 runs across the columns. An array with shape (3, 5) has 3 rows and 5 columns.

.sum() with no axis adds every number into one total. With axis=0 it adds down each column and gives back one total per column. With axis=1 it adds along each row and gives back one total per row. Either way, the axis you name disappears from the shape.

orders = np.array([[2, 0, 1],
                   [4, 3, 5]])     # shape (2, 3)
print(orders.sum())                # 15
print(orders.sum(axis=0))          # [6 3 6]   one per column, shape (3,)
print(orders.sum(axis=1))          # [ 3 12]   one per row, shape (2,)

In this lesson, sales holds 3 products (the rows) over 5 days (the columns). The starting code prints the table, its shape and the total of all sales. When you're done, the program prints:

[[5 3 4 6 2]
 [1 0 2 1 3]
 [8 6 9 7 5]]
Sales shape: (3, 5)
All sales: 62
Per day: [14  9 15 14 10]
Per day shape: (5,)
Per product: [20  7 35]
Per product shape: (3,)

Your task: sum sales along axis 0 into per_day and along axis 1 into per_product, and print each result and its .shape.


Assignment
Follow the Coding Tutorial to total the sales table per day with axis=0 and per product with axis=1.


Hint
Ask which axis has to disappear. A total per day adds up the 3 products in each column, so the rows (axis 0) go. A total per product adds up the 5 days in each row, so the columns (axis 1) go.


STEP 1 OF 6
    Ctrl + Enter to check

    Np Axis in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free