Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn Index Array

In NumPy, array indexing is a powerful feature that allows you to access and manipulate elements within multi-dimensional arrays (also known as ndarrays). NumPy provides several ways to index arrays, including basic indexing, slicing, advanced indexing, and boolean indexing.



Basic Indexing: NumPy arrays can be indexed similarly to Python lists using square brackets []. You can access individual elements or slices of elements by providing the indices within the brackets.

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Accessing individual elements
print(arr[0]) # Output: 1
# Accessing slices
print(arr[1:4]) # Output: [2 3 4]


Slicing: NumPy allows you to slice arrays to extract sub-arrays. Slicing is specified using the colon : operator.

# 2D array
arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Slicing rows and columns
print(arr_2d[:2, 1:]) # Output: [[2 3]
# [5 6]]


Advance Indexing: NumPy provides advanced indexing techniques like integer indexing and boolean indexing. Integer indexing allows you to select arbitrary elements using arrays of indices, while boolean indexing selects elements based on a boolean mask.

# Integer indexing
print(arr[[0, 2, 4]]) # Output: [1 3 5]
# Boolean indexing
mask = arr > 2
print(arr[mask]) # Output: [3 4 5]







Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java