NumPy is a popular Python library for data science for array, vector, and matrix computations. This puzzle introduces **basic indexing of elements** in NumPy arrays.

**Problem Formulation: **How to index elements in NumPy arrays?

## Indexing 1D Arrays with Positive Indices

The most simple use of indexing is with the square bracket notation and positive integers:

>>> import numpy as np >>> a = np.array([1, 2, 3]) >>> a array([1, 2, 3]) >>> a[0] 1 >>> a[1] 2 >>> a[2] 3

If you use a positive index larger or equal than the number of elements in the array, Python will throw an `IndexError`

:

>>> import numpy as np >>> a = np.array([1, 2, 3]) >>> a[3] Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> a[3] IndexError: index 3 is out of bounds for axis 0 with size 3

## Indexing 1D Arrays with Negative Indices

You can also use negative indices to access the array elements, starting with the last element and moving to the left:

>>> import numpy as np >>> a = np.array([8, 7, 5, 4, 9, 1, 9, 5]) >>> a[-1] 5 >>> a[-2] 9 >>> a[-3] 1 >>> a[-4] 9 >>> a[-5] 4 >>> a[-6] 5 >>> a[-7] 7 >>> a[-8] 8

If you move further into the negative, Python will throw an `IndexError`

:

>>> a[-9] Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> a[-9] IndexError: index -9 is out of bounds for axis 0 with size 8

## Indexing 2D Arrays NumPy

If you use two-dimensional arrays, you can index individual elements with the square bracket notation and comma-separated index values, one per axis. The first index value gives the row index and the second index value gives the column index:

>>> import numpy as np >>> a = np.array([[42, 8, 7], [99, 3, 4]]) >>> a[0, 0] 42 >>> a[1, 2] 4 >>> a[1, 1] 3

You can also use negative indexing on one or both axes.

>>> a[-1, -1] 4

If you access elements outside the bound of the maximal possible index, Python raises an `IndexError`

:

>>> a[2, 1] Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> a[2, 1] IndexError: index 2 is out of bounds for axis 0 with size 2

## NumPy Array Indexing Multi-dimensional Arrays

If you use multi-dimensional arrays, you can index individual elements with the square bracket notation and comma-separated index values, one per axis.

>>> import numpy as np >>> a = [[[1, 1], [2, 3]], [[4, 3], [8, 9]]] >>> a = np.array(a) >>> a[0, 0, 0] 1 >>> a[0, 0, 1] 1 >>> a[0, 1, 0] 2 >>> a[0, 1, 1] 3 >>> a[1, 0, 0] 4 >>> a[1, 0, 1] 3 >>> a[1, 1, 0] 8 >>> a[1, 1, 1] 9

**As a rule of thumb:** the first element in the comma-separated square bracket notation identifies the outermost axis, the second element the second-outermost axis, and so on.

## NumPy Array Indexing Puzzle

Train your skills by solving the following NumPy puzzle about indexing and basic array arithmetic:

import numpy as np # air quality index AQI data hong_kong = np.array([42, 40, 41, 43, 44, 43]) new_york = np.array([30, 31, 29, 29, 29, 30]) montreal = np.array([11, 11, 12, 13, 11, 12]) hk_mean = (hong_kong[0] + hong_kong[-1]) / 2.0 ny_mean = (new_york[1] + new_york[-3]) / 2.0 m_mean = (montreal[1] + montreal[-0]) / 2.0 print(hk_mean) print(ny_mean) print(m_mean)

*What is the output of this puzzle?*

*Beginner Level* (solution below)

You can solve this puzzle on our interactive Finxter app and track your skill level here:

The puzzle analysis data from the real-time air quality index (AQI) for the three cities Hong Kong, New York, and Montreal. The index data aggregates various factors that influence the air quality such as respirable particulate matter, ozone, and nitrogen dioxide. The goal is to compare the air quality data for the three cities. To show how indexing works, we use different indexing schemes to access two data values for each city. Then, we normalize the data by 2.0.

You can use positive or negative indices. For positive indices, use 0 to access the first element and increment the index by 1 to index each subsequent element. For negative indices, use -1 to access the last element and decrement the index by 1 to access each previous element. It’s as simple as that.

Are you a master coder?

Test your skills now!

## Related Video

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.