Skip to the workspace
Pebellslearn by building
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.

python data analysis / Indexing and Slicing

Explore each scene at your own pace.

01 · The rule

The rule

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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.