In this tutorial you will learn:
Access NumPy Array
The elements of NumPy Array can be accessed by indexing, it’s very similar to accessing an element in an array. We already know that the index of an array start with zero.
Access a 1-D array is very simple and straight forward we just need to pass the index in square brackets and print the value.
- import numpy as np
- arr = np.array([10, 8, 7, 2])
- print("** NumPy Show 1-D array access**”)
- print("Third element is: ", arr)
In order to access 2-D array using index we use the first index in square brackets to identify the first level array and second index in square brackets to identify the second level array.
- nparr1 = np.array([[9,5,6,7], [2,3,1,6]])
- print("\n\n** NumPy 2-D Array Access **")
- print("2nd Array's of Last Element", nparr1[1, 3])
For 3-D array we can use 3 indexes just as shown in the next example.
- nparr3 = np.array([[[3, 3, 3], [2, 8, 1]], [[5, 1, 3], [0, 31, 42]]])
- print("\n\n** NumPy 3-D Array Access **")
- print("2nd Element of first array then 1st element of second array\n and then print 2nd element of 3rd array", nparr3[1, 0, 1])
Accessing Arrays with Negative Index
Negative Indexes work from right to left and the can also be used to access NumPy arrays. The index on the extreme right starts with -1. Let’s look at an example to see is how we can use the negative indexing.
- print("\n\n** Numpy Arra Access using negative indexing **")
- nparrNeg = np.array([[6,9,2,8,5], [1,22,44,55,0]])
- print("Second element from 1st Array: ", nparrNeg[-2, -4])
Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.
Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.
FOR YOUR OWN SAFETY, PLEASE:
1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.