Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 158 - 2615_KEC
P. 158

    Accessing Elements in 1D Arrays

                      A 1D NumPy array is a sequence of values with positions called indices which starts at 0. We
                      access elements by using these indices in square brackets like arr[0] for the first element. Negative
                      indices count from the end so arr[-1] gives the last element.

                          Program.py

                       File  Edit  Format   Run    Options   Window    Help

                       import numpy as np                                               Output
                       arr = np.array([10, 20, 30, 40, 50])
                                                                                     10
                       print(arr[0])

                      Accessing Elements in Multidimensional Arrays

                      2D Arrays:

                      Elements can be accessed by specifying both row and column indices like matrix[row, column].

                          Program.py
                       File  Edit  Format    Run   Options   Window    Help

                       import numpy as np
                       matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
                       print(matrix[1, 2])

                          Output

                       6

                      3D Arrays:

                      Elements can be accessed by specifying three indices representing depth, row and column, like

                      array[depth, row, column].
                      In a 3D array, data is arranged in the form of multiple 2D layers stacked together. Each element

                      is identified by its position across three dimensions:

                          Depth (which layer),
                          Row (which horizontal line),

                          Column (which vertical position in that row).

                      156   Premium Edition-VIII

| 153 154 155 156 157 158 159 160 161 162 163 |