Introducing NumPy, Part 2: Indexing Arrays | by Lee Vaughan | Sep, 2024


Quick Success Data Science

Slicing and dicing like a pro

A cartoon of a happy Rubik’s cube, representing an ndarray, shedding lots of little cubes.
Indexing an array by DALL-E3

NumPy is Python’s foundational library for numerical calculations. With NumPy, the heavy lifting is handled by arrays, essentially tables of elements of the same data type. Arrays are optimized for performance, permitting faster mathematical and logical operations than traditional Python data types, like lists.

In Part 1, we covered how to create arrays, describe them, and access their attributes using dot notation. In this article, we’ll examine how to access the elements in arrays using indexes and slices, so you can extract the value of elements and change them using assignment statements. Array indexing uses square brackets [], just like Python lists.

As a refresher from Part 1, here is a graphical representation of a 1D, 2D, and 3D array, with the axes annotated. You’ll need to understand the axes’ directions to index properly.

Diagram showing graphic examples of a 1D NumPy array (as a sequence of numbers), a 2D array (as a table of numbers), and a 3D array (as a cube of numbers).
Graphical representation of 1D, 2D, and 3D arrays (from Python Tools for Scientists) (This and several future links to my book are affiliate links)



Source link

Be the first to comment

Leave a Reply

Your email address will not be published.


*