07 Python Numpy Array

NumPy is a Python library that is the core library for scientific computing in Python.  The library’s name is actually  short for “Numerical Python”. There are other libraries such as SciPy, Scikit-Learn, Pandas, etc. You can use numpy by downloading  Anaconda Python distribution.  Datacamp has a very good tutorial about Python Numpy Array Tutorial.


01  Example: 

import numpy as np

a = np.array( [1,2,3] )     # a 1D array initialised using a list [1,2,3]

b = np.array( [(1,2,5.8), (4,5,6)] ) # a 2D array initialised using a touple

#here, one of the element is float, as a result all the elements in array are treated as float

c = np.array( [(1,2,5), (4,5,6), (7,3,4)], dtype = int )  

# dtype can be, int, float, or complex

print( a )
print( b )
print( c )

print( c.T )              # it makes transpose of matrix c

and you will see the following output,










02 Example: 

import numpy as np

a = np.ones( (3, 2) )             # a 2D array with 3 rows, 2 columns, filled with ones
b = np.zeros( (3,  2) )           # a 2D array with 3 rows, 2 columns, filled with zeros
c = np.array( [1, 2, 3] )         # a 1D array initialized using a list [1,2,3]
d = np.linspace( 0, 10, 6)     # an array with 6 points  including 0 and 10

e = np.eye( 3 )             
# The eye(N) function creates an N*N two-dimensional 
# identity matrix with ones along the diagonal:
   
f = np.array( [ (1,2,5), (4,5,6) ],  dtype = complex )  
 
 
print(a, "\n")  

print(b, "\n") 

print(c, "\n")

print(d, "\n")

print(e, "\n")

print(f, "\n")


and you will see the following output,















03 Example: 

Accessing specific element from array.

import numpy as np

a = np.array( [1, 2, 3] )                      # a 1D array initialised using a list [1,2,3]

b = np.array( [ (3,2,5.8), (4,5,6) ] )  # a 2D array initialised using a touple

#here, one of the element is float, hence all the elements in array are treated as float

c = np.array( [ (1,2,5), (4,5,6), (7,3,4) ] ) # dtype can be, int, float, or complex

d = np.diag( np.array( [6, 2, 3, 4] ) )

print( a )
print( b )
print( c )
print( d )

print( a[ 0] )
print( b[ 0,0] )
print( c[ 2,2] )
print( d[ 2,2] )

and you will see the following output,