To work with SciPy, do I need to import the NumPy functions explicitly?

ScipyScientific ComputingOpen Source

When SciPy is imported, you do not need to explicitly import the NumPy functions because by default all the NumPy functions are available through SciPy namespace. But as SciPy is built upon the NumPy arrays, we must need to know the basics of NumPy.

As most parts of linear algebra deals with vectors and matrices only, let us understand the basic functionalities of NumPy vectors and matrices.

Creating NumPy vectors by converting Python array-like objects

Let us understand this with the help of following example−

Example

import numpy as np
list_objects = [10,20,30,40,50,60,70,80,90]
array_new = np.array(list_objects)
print (array_new)

Output

[10 20 30 40 50 60 70 80 90]

NumPy array creation

NumPy has various functions to create arrays from scratch. Let us understand them along with examples −

  • Using zeros()

This function will create an array filled with 0 values with the specified shape.

Example

import numpy as np
print (np.zeros((3, 4)))

Output

[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
  • Using ones()

This function will create an array filled with 1 values with the specified shape.

Example

import numpy as np
print (np.ones((3, 4)))

Output

[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
  • Using arange()

This function will create an array with regularly incrementing values.

Example

import numpy as np
print (np.arange(15))

Output

[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
  • Using linspace()

This function will create arrays spaced equally between the specified start and end values.

Example

import numpy as np
print (np.linspace(1.0, 3.0, num=5))

Output

[1. 1.5 2. 2.5 3. ]

Creating matrices and applying some functions over matrices using NumPy

A matrix is a specialized two-dimensional (2D) array. Matrices retains its nature through all the operations applied over it.

Creating a matrix

Let us understand this with the help of following example −

Example

import numpy as np
matrix = np.matrix('10 20; 30 40')
print(matrix)

Output

[[10 20]
[30 40]]

Transpose a Matrix

This function will return the transpose of a matrix. The below example will transpose of the above created matrix −

Example

matrix.T

Output

matrix([[10, 30],
[20, 40]])

Multiplication of two Matrices

We can use the dot() function of NumPy for doing multiplications of two matrices. Let us understand this with the help of following example −

Example

import numpy as np
matrix1 = np.array([[1,6,9],[3,4,10]])
matrix2 = np.array([[2,5],[4,7],[7,8]])
matrix3 = np.dot(matrix1,matrix2)
print(matrix3)

Output

[[ 89 119]
[ 92 123]]

You can learn in detail about NumPy at https://www.tutorialspoint.com/numpy/index.htm .

raja
Published on 23-Nov-2021 12:39:42

Advertisements