Indexing & Slicing in NumPy

Python tutorial · PySpark.in

Indexing & Slicing in NumPy

Indexing and slicing are fundamental operations in NumPy that allow users to access, retrieve, and manipulate elements of an array efficiently. These operations make NumPy suitable for scientific computing, data analysis, and machine learning.

1.Basic Indexing

Basic indexing in NumPy refers to the process of accessing individual elements of an array using their index position. NumPy follows zero-based indexing, where the first element of the array is accessed using index 0.

Explanation

Example

```

import numpy as np

arr = np.array([10, 20, 30, 40])

print(arr[0])

print(arr[2])

```

2.Negative Indexing

Negative indexing is a method in NumPy that allows accessing elements from the end of an array using negative index values, where -1 represents the last element of the array.

Explanation

Example

```

print(arr[-1])

print(arr[-2])

```

3. Slicing

Slicing in NumPy is the technique of extracting a subset of elements from an array using a specified range defined by start index, stop index, and step size.

Syntax

```

Hide

array[start : stop : step]

```

Explanation

Examples

```

arr = np.array([0, 1, 2, 3, 4, 5])

print(arr[1:4])

print(arr[:3])

print(arr[::2])

print(arr[::-1])

```

Important Note

Slicing in NumPy returns a view of the original array, not a copy.

4.Indexing in 2D Arrays

Indexing in a two-dimensional NumPy array involves accessing elements using two indices, where the first index represents the row number and the second index represents the column number.

Example

```

mat = np.array([[1, 2, 3],

[4, 5, 6]])

print(mat)

```

Accessing Single Element

```

print(mat[0, 1])

```

Row and Column Access

```

print(mat[0])

print(mat[:, 1])

```

Slicing in 2D Array

```

print(mat[0:2, 1:3])

```

5.Indexing in 3D Arrays

Indexing in a three-dimensional NumPy array involves accessing elements using three indices, commonly representing depth, row, and column.

Example

```

arr3d = np.array([

[[1, 2], [3, 4]],

[[5, 6], [7, 8]]

])

print(arr3d)

```

Accessing Single Element

```

print(arr3d[0, 1, 1])

```

Accessing a 2D Slice

```

print(arr3d[1])

```

Slicing in 3D Array

```

print(arr3d[:, :, 0])

```

Difference Between Indexing and Slicing

Feature

Indexing

Slicing

Purpose

Access single element

Extract multiple elements

Output

Scalar value

Sub-array

Syntax

arr[i]

arr[start:stop]

Memory

Independent value

View of original array


More Python tutorials

All tutorials · Try the free PySpark compiler · Practice challenges