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 valueBy 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 valueIn 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.