NumPy – Indexing & Slicing

NumPy - Indexing & Slicing

In this chapter, we will discuss about NumPy – Indexing & Slicing. Contents of ndarray object can be accessed and modified by indexing or slicing, just like Python’s in-built container objects. Basic Slicing and Advanced Indexing in NumPy www.matplotlib.org.

As mentioned earlier, items in the ndarray object follow a zero-based index. Three types of indexing methods are available − field access, basic slicing and advanced indexing.

NumPy – Indexing & Slicing Examples –

Example 1

import numpy as np 
a = np.arange(10) 
s = slice(2,7,2) 
print a[s]

Its output is as follows −

[2  4  6]

In the above example, a ndarray object is prepared by arange() function.

The same result can also be obtained by giving the slicing parameters separated by a colon : (start:stop:step) directly to the ndarray object.

Example 2

import numpy as np 
a = np.arange(10) 
b = a[2:7:2] 
print b

Here, we will get the same output −

[2  4  6]

Example 3

# slice single item 
import numpy as np 

a = np.arange(10) 
b = a[5] 
print b

Its output is as follows −

5

Example 4

# slice items starting from index 
import numpy as np 
a = np.arange(10) 
print a[2:]

Now, the output would be −

[2  3  4  5  6  7  8  9]

Example 5

# slice items between indexes 
import numpy as np 
a = np.arange(10) 
print a[2:5]

Here, the output would be −

[2  3  4] 

The above description applies to multi-dimensional ndarray too.

Example 6

import numpy as np 
a = np.array([[1,2,3],[3,4,5],[4,5,6]]) 
print a  

# slice items starting from index
print 'Now we will slice the array from the index a[1:]' 
print a[1:]

The output is as follows −

[[1 2 3]
 [3 4 5]
 [4 5 6]]

Now we will slice the array from the index a[1:]
[[3 4 5]
 [4 5 6]]

Slicing can also include ellipsis (…) to make a selection tuple of the same length as the dimension of an array.

Example 7

# array to begin with 
import numpy as np 
a = np.array([[1,2,3],[3,4,5],[4,5,6]]) 

print 'Our array is:' 
print a 
print '\n'  

# this returns array of items in the second column 
print 'The items in the second column are:'  
print a[...,1] 
print '\n'  

# Now we will slice all items from the second row 
print 'The items in the second row are:' 
print a[1,...] 
print '\n'  

# Now we will slice all items from column 1 onwards 
print 'The items column 1 onwards are:' 
print a[...,1:]

The output of this program is as follows −

Our array is:
[[1 2 3]
 [3 4 5]
 [4 5 6]] 
 
The items in the second column are: 
[2 4 5] 

The items in the second row are:
[3 4 5]

The items column 1 onwards are:
[[2 3]
 [4 5]
 [5 6]] 

Next Topic – Click Here

Leave a Reply