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.
Free plan: 30 tutor messages. PRO is unlimited.
