Indexing Arrays
Indexing picks values out of an array by position or by a test. A test picks every value that passes it.
One value by position
Position 0 is the first value. Position -1 is the last value.
import numpy as np
units = np.array([2, 1, 3, 2, 5])
print(units[0])
print(units[-1])
Values that pass a test
The test keeps values above 2. The rest drop out.
import numpy as np
units = np.array([2, 1, 3, 2, 5])
print(units > 2)
print(units[units > 2])
Several positions at once
A list of positions picks those values in that order. This is fancy indexing.
import numpy as np
units = np.array([2, 1, 3, 2, 5])
print(units[[0, 2, 4]])
Example
import io
import numpy as np
import pandas as pd
SALES_CSV = """
order_id,date,product,category,units,price,region
101,2026-01-05,Tea,Drink,2,4.50,North
102,2026-01-06,Coffee,Drink,1,6.00,South
103,2026-01-07,Mug,Home,3,12.00,East
104,2026-01-08,Notebook,Office,2,8.50,West
105,2026-01-09,Pen,Office,5,2.00,North
106,2026-01-12,Lamp,Home,1,24.00,South
107,2026-01-13,Tea,Drink,4,4.50,East
108,2026-01-14,Coffee,Drink,2,6.00,West
109,2026-01-15,Mug,Home,1,12.00,North
110,2026-01-16,Notebook,Office,3,8.50,South
111,2026-01-19,Pen,Office,2,2.00,East
112,2026-01-20,Lamp,Home,2,24.00,West"""
sales = pd.read_csv(io.StringIO(SALES_CSV))
units = np.array(list(sales["units"]))
big = units[units >= 3]
print(big)
print(big.sum())
Key points
- Use square brackets with a position to pick one value.
- Positions start at 0, and -1 means the last value.
- A test in the brackets keeps the values that pass it.
- Use a list of positions to pick several values at once.
In this example, the sales table loads from its CSV text. The units column becomes an array. The test keeps orders of 3 units or more. Four orders pass, and their units add to 15.
Note
Picking with a test gives a copy. Changing the copy leaves the first array alone.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does np.array([2, 1, 3])[np.array([2, 1, 3]) > 1] print?