Introduction
So, the focus is still about using NumPy array variable in this article. There are several previous articles available which is also focusing on how to use several attributes exist in NumPy array. All of those attributes exist with their own function or usage. But in this article, the focus is just to show how to be able to access or to perform indexing in NumPy array. It is very useful for searching several elements according to the index, location or position of the specific elements exist in the NumPy array.
How to Access or Index NumPy Array
In this case, before going on to display how to access or index the NumPy array, it is important to have the NumPy array first. In order to have the NumPy array first, it is important to have the NumPy library also in the first place. Before going on to that point, just read an article with the title of ‘How to Use NumPy’ in this link to be able to do that. After doing that, the following is the demonstration to access or to index the NumPy array :
-
Run the Command Prompt for accessing the command line interface. In this context, the example will be in a command. In Microsoft Windows operating system, just run the Command Prompt as in the following appearance :
Microsoft Windows [Version 10.0.22000.856] (c) Microsoft Corporation. All rights reserved. C:\Users\Personal>
-
Type python to run and get in into the Python command console as follows :
Microsoft Windows [Version 10.0.22000.856] (c) Microsoft Corporation. All rights reserved. C:\Users\Personal>python Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>>
-
After getting in to the Python command console, do not forget to import the NumPy array as follows :
Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import numpy as np
-
After getting the NumPy library, just define the NumPy array as follows :
Microsoft Windows [Version 10.0.22000.856] (c) Microsoft Corporation. All rights reserved. C:\Users\Personal>python Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import numpy as np >>> numpy_array = np.array([1]) >>> print(numpy_array[0]) 1 >>>
Actually, the NumPy array element’s access is using an indexing rule. So, in order to access the NumPy array element, it has to follow the index rule which is using the correct index. In other words, accessing a NumPy array element must be refer to its index number. The indexes rule in NumPy arrays always start with 0. Therefore, in order to access the first element, it will have to use index 0. And then, in order to access the next element, it will have to use index 1 and so on.