Indexing and Slicing
Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 8 of 60.
Arrays index like lists, from 0. Five days of piano practice, in minutes:
practice = np.array([20, 0, 35, 15, 40])
print(practice[0]) # first
print(practice[-1]) # last
print(practice[1:4]) # positions 1 to 3This prints:
20
40
[ 0 35 15]A 2D array takes a row and a column in one pair of brackets, row first. Each row of stock is a shop, each column a product:
stock = np.array([[5, 8, 2, 6], [9, 1, 4, 3], [7, 0, 6, 8]])
print(stock[1, 2]) # one value
print(stock[0]) # a whole row
print(stock[:, 3]) # a whole columnThis prints:
4
[5 8 2 6]
[6 3 8]In the row place, a colon means every row and a slice like 0:2 some of them. So data[:, column] is one feature for every sample.
Challenge
EasyA hotel's report is wrong. bookings has a row per week and a column per day, Monday to Sunday. The program reads a week and a day, counted from 1.
Each line has one bug. Fix them to match the labels:
Week: the whole weekWeekend: its last two days, a sliceDay: that day, every weekBooked: that one day
For week 3, day 5:
Week 3: [11 12 13 17 20 24 26]
Weekend: [24 26]
Day 5: [18 19 20 21]
Booked: 20Try it yourself
import numpy as np
# Rooms booked at a small hotel: one row per week (weeks 1 to 4),
# one column per day (days 1 to 7, Monday to Sunday)
bookings = np.array([
[12, 15, 14, 16, 18, 25, 27],
[10, 13, 15, 14, 19, 26, 28],
[11, 12, 13, 17, 20, 24, 26],
[9, 14, 16, 15, 21, 27, 29],
])
week = int(input())
day = int(input())
# The report prints the wrong numbers: fix the lines below
row = bookings[week]
print(f"Week {week}: {row}")
print(f"Weekend: {row[5:6]}")
print(f"Day {day}: {bookings[day - 1]}")
print(f"Booked: {bookings[day - 1, week - 1]}")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Data and Plots
2NumPy Arrays
Creating ArraysShape and SizeRanges of NumbersIndexing and SlicingRecap: Temperature GridPractice on your own: Online Python compiler