Python Practice › NumPy Programs › Program 61
The ith element of a 2-D array
Write a NumPy program to find the ith element (counting row by row) of a 2-D array.
Input
[[4, 8, 7], [2, 3, 6]], i = 5
Output
3 (np.int64(1), np.int64(1))
Approach
flat[i - 1]for the 5th element, ornp.unravel_indexfor its row and column.
Solution
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.
Learn the concept
New to this topic? Read the lesson, then come back.