Menu
CoddyTech

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 3

This 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:

A grid of 3 rows and 4 columns of numbers; the cell in row 1, column 2 holding 4 is shaded darkest, and all of column 3, holding 6, 3 and 8, is shaded

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 column

This 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 icon

Challenge

Easy

A 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 week
  • Weekend: its last two days, a slice
  • Day: that day, every week
  • Booked: 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: 20

Try 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]}")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and Plots

Practice on your own: Online Python compiler