NumPy Array Indexing and Slicing of Python NumPy Module. The following shows various universal indexing and slicing technic of the NumPy array of Python NumPy module.
import numpy as np
Code:
a = np.arange(10)**3
a
Output:
array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729])
Code:
a[2]
Output:
8
Code:
a[2:5]
Output:
array([ 8, 27, 64])
Code:
a[:6:2] = -1000
a
Output:
array([-1000, 1, -1000, 27, -1000, 125, 216, 343, 512, 729])
Code:
a[ : :-1]
Output:
array([ 729, 512, 343, 216, 125, -1000, 27, -1000, 1, -1000])
Code:
def f(x,y):
return 10*x+y
b = np.fromfunction(f,(5,4),dtype=int)
b
Output:
array([[ 0, 1, 2, 3],
[10, 11, 12, 13],
[20, 21, 22, 23],
[30, 31, 32, 33],
[40, 41, 42, 43]])
Code:
b[2,3]
Output:
23
Code:
b[0:5, 1]
Output:
array([ 1, 11, 21, 31, 41])
Code:
b[0:3, 2]
Output:
array([ 2, 12, 22])
Code:
b[ : ,1]
Output:
array([ 1, 11, 21, 31, 41])
Code:
b[1:3, : ]
Output:
array([[10, 11, 12, 13],
[20, 21, 22, 23]])
Code:
b[-1]
Output:
array([40, 41, 42, 43])
Code:
c = np.array( [[[ 0, 1, 2], # a 3D array (two stacked 2D arrays)
[ 10, 12, 13]],
[[100,101,102],
[110,112,113]]])
c.shape
Output:
(2, 2, 3)
Code:
c[1,...] # same as c[1,:,:] or c[1]
Output:
array([[100, 101, 102],
[110, 112, 113]])
Code:
c[...,2] # same as c[:,:,2]
Output:
array([[ 2, 13],
[102, 113]])