Indexing Using Index arrays

Indexing can be done in NumPy by using an array as an index.

Numpy arrays can be indexed with other arrays or any other sequence with the exception of tuples. The last element is indexed by -1 second last by -2 and so on.

In the case of slicing, a view or shallow copy of the array is returned but in an index array, a copy of the original array is returned.

Example: Indexing using an index array

Python




import numpy as np
# Create a sequence of integers from 10 to 1 with a step of -2
a = np.arange(10, 1, -2
print("\n A sequential array with a negative step: \n",a)
# Indexes are specified inside the np.array method.
newarr = a[np.array([3, 1, 2 ])]
print("\n Elements at these indices are:\n",newarr)


Output : 

A sequential array with a negative step:
[10 8 6 4 2]
Elements at these indices are:
[4 8 6]

Basic Slicing and Advanced Indexing in NumPy

Indexing a NumPy array means accessing the elements of the NumPy array at the given index.

There are two types of indexing in NumPy: basic indexing and advanced indexing.

Slicing a NumPy array means accessing the subset of the array. It means extracting a range of elements from the data.

In this tutorial, we will cover basic slicing and advanced indexing in the NumPy. NumPy arrays are optimized for indexing and slicing operations making them a better choice for data analysis projects.

Prerequisites 

Numpy in Python Introduction

Similar Reads

Indexing an NumPy Array

Indexing is used to extract individual elements from a one-dimensional array....

Indexing Using Index arrays

Indexing can be done in NumPy by using an array as an index....

Types of Indexing in NumPy Array

...

Basic Slicing and indexing

There are two types of indexing used in Python NumPy:...

Advanced indexing

Basic slicing and indexing is used to access a specific element or range of elements from a NumPy array....

Contact Us