Start learning free

LESSON 2 OF 165 · MACHINE LEARNING: NUMPY

Pick Items and Slices in Python

Practice

You pick one number out of an array by its position in square brackets, just like in a list. Positions start at 0, and negative positions count back from the end: a[0] gives back the first item and a[-1] the last. A slice a[start:stop] gives back a smaller array with the items from position start up to, but not including, stop.

An array can also be a table: a 2-D array, made from a list of rows. To pick one item, give its row and its column in one pair of brackets: a[row, col]. A lone : means every row, so a[:, col] gives back a whole column, and one number, a[row], gives back a whole row.

stock = np.array([[4, 0, 9],
                  [2, 7, 1]])
print(stock[0, 2])   # 9
print(stock[:, 1])   # [0 7]
print(stock[1])      # [2 7 1]

In this lesson, sales has one row per product (row 1 is the Lamp) and one column per day, from Monday (column 0) to Thursday (column 3). Your program must print:

Prices: [12  7 29  2 15 22]
First: 12
Last: 22
Positions 1 to 3: [ 7 29  2]
[[5 3 4 6]
 [1 0 2 1]
 [8 6 9 7]]
Lamp on Wednesday: 2
Monday: [5 1 8]
Lamp: [1 0 2 1]

Your task: below the first print, print the first price, the last price and the prices at positions 1 to 3. Below print(sales), print the Lamp's sales on Wednesday, the Monday column and the Lamp's row.


Assignment
Follow the Coding Tutorial to pick single items, a slice, a column and a row out of the two arrays.


Hint
Count from 0: the Lamp is row 1 and Wednesday is column 2. In a 2-D array the row comes first, then the column, both in one pair of brackets. A slice for positions 1 to 3 stops at 4.


STEP 1 OF 6
    Ctrl + Enter to check

    Np Indexing 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