Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
NumPy Arrays  ›  Lesson

Indexing and Slicing

Indexing & Slicing 14 minSquare brackets select array values by position, by a start-stop-step range that excludes the stop, or by a boolean mask built from a condition.

Indexing and Slicing

"Show me only the big sales." "What happened on the last day?" Most analysis questions start by picking out part of the data. NumPy gives three ways to pick: by position, by range, and by condition.

The rule

Brackets pick by position, by range, or by a True/False mask.

By position, counting from 0. Negative numbers count from the end:

copies = np.array([3, 5, 2, 4, 1, 6, 2, 3])
copies[0]     # 3
copies[-1]    # 3, the last value

By range, with a slice start:stop:step. The stop is excluded:

copies[2:5]   # [2 4 1]   positions 2, 3 and 4
copies[:3]    # [3 5 2]   from the start
copies[::2]   # [3 2 1 2] every second value

In two dimensions, give a row part and a column part separated by a comma:

grid = copies.reshape(2, 4)   # [[3 5 2 4]
                              #  [1 6 2 3]]
grid[1, 2]    # 2, row 1 and column 2
grid[:, 0]    # [3 1], every row, column 0
grid[0, 1:3]  # [5 2]

By mask: put an array of booleans inside the brackets, and only positions marked True are kept.

copies[copies > 3]                    # [5 4 6]
copies[(copies >= 2) & (copies <= 3)] # [3 2 2 3]

Combine conditions with & (and), | (or) and ~ (not), and wrap each condition in parentheses. Python's words and and or do not work on whole arrays.

The shortcut

For a slice, subtract to count: a[start:stop] returns stop − start values. For a mask, say it as a sentence: "copies where copies is greater than 3".

Sales from the middle of the weekStep 1 of 4
  1. State the range

    We want positions 2 through 5 inclusive.

A quiet trap: a slice is a view of the same memory, not a copy. Changing part = copies[:3] then part[0] = 99 also changes copies[0]. Use .copy() when you want an independent piece.

Drills

Answer fast — trust the rule.

quick drill

With copies = [3 5 2 4 1 6 2 3], what is copies[-2]?

quick drill

How many values does copies[1:6] return?

quick drill

With grid = [[3 5 2 4] [1 6 2 3]], what is grid[:, 1]?

quick drill

Which expression keeps sales of 2 to 4 copies, both ends included?

Remember

  • Brackets pick by position, by range, or by a True/False mask.
  • Subtract to count a slice; say a mask out loud as a sentence.
  • Slices are views: use .copy() before changing a piece you want to keep separate.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainPicking the big sales

Using copies = np.array([3, 5, 2, 4, 1, 6, 2, 3]), explain how to get the sales of at least 4 copies, what the result is, and why copies >= 4 and copies <= 6 would not work.