Python Practice › NumPy Programs › Program 61

The ith element of a 2-D array

EasyNumPy Programs · 61 of 100

Write a NumPy program to find the ith element (counting row by row) of a 2-D array.

Advertisement
Input
[[4, 8, 7], [2, 3, 6]], i = 5
Output
3 (np.int64(1), np.int64(1))

Approach

  1. flat[i - 1] for the 5th element, or np.unravel_index for its row and column.

Solution

Python
import numpy as npa = np.array([[4, 8, 7], [2, 3, 6]])i = 5print(a.flat[i - 1], np.unravel_index(i - 1, a.shape))
Output
3 (np.int64(1), np.int64(1))

Line by line

Line 4

The 5th element (index 4) is in row 1, column 1.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More numpy programs

← All 100 NumPy Programs