Skip to content
Related Articles

Related Articles

Improve Article

Select an element or sub array by index from a Numpy Array

  • Last Updated : 29 Aug, 2020

The elements of a NumPy array are indexed just like normal arrays. The index of the first element will be 0 and the last element will be indexed n-1, where n is the total number of elements.

Selecting a single element from a NumPy array

Each element of these ndarrays can be accessed using its index number.

Example: The following code shows how to access an element of a NumPy array.

Python3




import numpy as np
  
# NumPy Array
numpyArr = np.array([1, 2, 3, 4])
print("numpyArr[0] =", numpyArr[0])
print("numpyArr[-1] =", numpyArr[-1])

Output:



numpyArr[0] = 1
numpyArr[-1] = 4

In the first case, we accessed the first element of the array using its index number. In the second case we accessed the last element of the array by using negative indexes.

Selecting a sub array from a NumPy array (Slicing)

To get a sub-array, we pass a slice in place of the element index.

Syntax:

numpyArr[x:y]

Here x and y are the starting and last index of the required sub-array.

Example:

Python3




import numpy as np
  
# NumPy Array
numpyArr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
  
# the slice 3:6 is passed instead 
# of index
print("Sub-Array=", numpyArr[3:6])

Output:

Sub-Array= [4 5 6]

A sub-array starting from the 3rd index up to the 6th index ( excluding the last the 6th index ) was selected. You can slice a sub-array starting from the first element by leaving the starting index blank.



Example: The following code selects a sub-array starting from the first element. 

Python3




import numpy as np
  
numpyArr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
  
# works same as 0:6
print("Sub-Array=", numpyArr[:6])

Output:

Sub-Array= [1 2 3 4 5 6]

Similarly, leaving the left side of the colon blank will give you an array up to the last element.

Example: The following code selects a sub-array starting from a particular index up to the last index.

Python3




import numpy as np
  
numpyArr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
  
# same as 3:9 or 3:n, where n is
# the length of array
print("Sub-Array=", numpyArr[3:])

Output:

Sub-Array= [4 5 6 7 8 9]

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :