100% found this document useful (1 vote)
149 views

Numpy Notes

NumPy is a Python package that provides multidimensional array and matrix objects as well as tools to work with these objects. It is used for scientific computing with Python. NumPy arrays enable fast operations on large data sets and matrices. NumPy can be installed via pip and is commonly used with other scientific Python packages like SciPy, Pandas, and Matplotlib. NumPy arrays, called ndarrays, provide n-dimensional grids of values that can perform fast operations. NumPy also provides functions for linear algebra, Fourier transforms, and random number generation.

Uploaded by

Cayden James
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
149 views

Numpy Notes

NumPy is a Python package that provides multidimensional array and matrix objects as well as tools to work with these objects. It is used for scientific computing with Python. NumPy arrays enable fast operations on large data sets and matrices. NumPy can be installed via pip and is commonly used with other scientific Python packages like SciPy, Pandas, and Matplotlib. NumPy arrays, called ndarrays, provide n-dimensional grids of values that can perform fast operations. NumPy also provides functions for linear algebra, Fourier transforms, and random number generation.

Uploaded by

Cayden James
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 170

What is NumPy

NumPy stands for numeric python which is a python package for the computation
and processing of the multidimensional and single dimensional array elements.

The need of NumPy


With the revolution of data science, data analysis libraries like NumPy, SciPy,
Pandas, etc. have seen a lot of growth. With a much easier syntax than other
programming languages, python is the first choice language for the data scientist.

NumPy provides a convenient and efficient way to handle the vast amount of data.
NumPy is also very convenient with Matrix multiplication and data reshaping. NumPy
is fast which makes it reasonable to work with a large set of data.

There are the following advantages of using NumPy for data analysis.

1. NumPy performs array-oriented computing.

2. It efficiently implements the multidimensional arrays.

3. It performs scientific computations.

4. It is capable of performing Fourier Transform and reshaping the data stored


in multidimensional arrays.

5. NumPy provides the in-built functions for linear algebra and random number
generation.

Nowadays, NumPy in combination with SciPy and Mat-plotlib is used as the


replacement to MATLAB as Python is more complete and easier programming
language than MATLAB.

NumPy Environment Setup


NumPy doesn't come bundled with Python. We have to install it using the python
pip installer. Execute the following command.

1. $ pip install numpy

It is best practice to install NumPy with the full SciPy stack. The binary distribution
of the SciPy stack is specific to the operating systems.

Windows
On the Windows operating system, The SciPy stack is provided by the Anaconda
which is a free distribution of the Python SciPy package.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
It can be downloaded from the official website: https://www.anaconda.com/. It is
also available for Linux and Mac.

The CanoPy also comes with the full SciPy stack which is available as free as well as
commercial license. We can download it by visiting the link:
https://www.enthought.com/products/canopy/

The Python (x, y) is also available free with the full SciPy distribution. Download it
by visiting the link: https://python-xy.github.io/

Linux
In Linux, the different package managers are used to install the SciPy stack. The
package managers are specific to the different distributions of Linux. Let's look at
each one of them.

Ubuntu
Execute the following command on the terminal.

1. $ sudo apt-get install python-numpy


2.
3. $ python-scipy python-matplotlibipythonipythonnotebook python-pandas
4.
5. $ python-sympy python-nose

Redhat
On Redhat, the following commands are executed to install the Python SciPy
package stack.

1. $ sudo yum install numpyscipy python-matplotlibipython


2.
3. $ python-pandas sympy python-nose atlas-devel

To verify the installation, open the Python prompt by executing python command on
the terminal (cmd in the case of windows) and try to import the module NumPy as
shown in the below image. If it doesn't give the error, then it is installed
successfully.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
NumPy Ndarray
Ndarray is the n-dimensional array object defined in the numpy which stores the
collection of the similar type of elements. In other words, we can define a ndarray as
the collection of the data type (dtype) objects.

The ndarray object can be accessed by using the 0 based indexing. Each element of
the Array object contains the same size in the memory.

Creating a ndarray object


The ndarray object can be created by using the array routine of the numpy module.
For this purpose, we need to import the numpy.

1. >>> a = numpy.array

Consider the below image.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
We can also pass a collection object into the array routine to create the equivalent
n-dimensional array. The syntax is given below.

1. >>> numpy.array(object, dtype = None, copy = True, order = None, subok


= False, ndmin = 0)

The parameters are described in the following table.

SN Parameter Description

1 object It represents the collection object. It can be a list, tuple, dictionary, set, et

2 dtype We can change the data type of the array elements by changing this optio

3 copy It is optional. By default, it is true which means the object is copied.

4 order There can be 3 possible values assigned to this option. It can be C (column

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
5 subok The returned array will be base class array by default. We can change this
this option to true.

6 ndmin It represents the minimum dimensions of the resultant array.

To create an array using the list, use the following syntax.

1. >>> a = numpy.array([1, 2, 3])

To create a multi-dimensional array object, use the following syntax.

1. >>> a = numpy.array([[1, 2, 3], [4, 5, 6]])

To change the data type of the array elements, mention the name of the data type
along with the collection.

1. >>> a = numpy.array([1, 3, 5, 7], complex)

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Finding the dimensions of the Array
The ndim function can be used to find the dimensions of the array.

1. >>> import numpy as np


2. >>> arr = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [9, 10, 11, 23]])
3.
4. >>> print(arr.ndim)

Finding the size of each array element


The itemsize function is used to get the size of each array item. It returns the
number of bytes taken by each array element.

Consider the following example.

Example
1. #finding the size of each item in the array

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
2. import numpy as np
3. a = np.array([[1,2,3]])
4. print("Each item contains",a.itemsize,"bytes")

Output:

Each item contains 8 bytes.

Finding the data type of each array item


To check the data type of each array item, the dtype function is used. Consider the
following example to check the data type of the array items.

Example
1. #finding the data type of each array item
2. import numpy as np
3. a = np.array([[1,2,3]])
4. print("Each item is of the type",a.dtype)

Output:

Each item is of the type int64

Finding the shape and size of the array


To get the shape and size of the array, the size and shape function associated with
the numpy array is used.

Consider the following example.

Example
1. import numpy as np
2. a = np.array([[1,2,3,4,5,6,7]])
3. print("Array Size:",a.size)
4. print("Shape:",a.shape)

Output:

Array Size: 7
Shape: (1, 7)

Reshaping the array objects

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
By the shape of the array, we mean the number of rows and columns of a multi-
dimensional array. However, the numpy module provides us the way to reshape the
array by changing the number of rows and columns of the multi-dimensional array.

The reshape() function associated with the ndarray object is used to reshape the
array. It accepts the two parameters indicating the row and columns of the new
shape of the array.

Let's reshape the array given in the following image.

Example
1. import numpy as np
2. a = np.array([[1,2],[3,4],[5,6]])
3. print("printing the original array..")
4. print(a)
5. a=a.reshape(2,3)
6. print("printing the reshaped array..")
7. print(a)

Output:

printing the original array..


[[1 2]
[3 4]
[5 6]]
printing the reshaped array..
[[1 2 3]
[4 5 6]]

Slicing in the Array


Slicing in the NumPy array is the way to extract a range of elements from an array.
Slicing in the array is performed in the same way as it is performed in the python
list.

Consider the following example to print a particular element of the array.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Example
1. import numpy as np
2. a = np.array([[1,2],[3,4],[5,6]])
3. print(a[0,1])
4. print(a[2,0])

Output:

2
5

The above program prints the 2nd element from the 0th index and 0th element from
the 2nd index of the array.

Linspace
The linspace() function returns the evenly spaced values over the given interval. The
following example returns the 10 evenly separated values over the given interval 5-
15

Example
1. import numpy as np
2. a=np.linspace(5,15,10) #prints 10 values which are evenly spaced over the g
iven interval 5-15
3. print(a)

Output:

[ 5. 6.11111111 7.22222222 8.33333333 9.44444444 10.55555556


11.66666667 12.77777778 13.88888889 15. ]

Finding the maximum, minimum, and sum of the


array elements
The NumPy provides the max(), min(), and sum() functions which are used to find
the maximum, minimum, and sum of the array elements respectively.

Consider the following example.

Example
1. import numpy as np
2. a = np.array([1,2,3,10,15,4])
3. print("The array:",a)
4. print("The maximum element:",a.max())

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
5. print("The minimum element:",a.min())
6. print("The sum of the elements:",a.sum())

Output:

The array: [ 1 2 3 10 15 4]
The maximum element: 15
The minimum element: 1
The sum of the elements: 35

NumPy Array Axis


A NumPy multi-dimensional array is represented by the axis where axis-0 represents
the columns and axis-1 represents the rows. We can mention the axis to perform
row-level or column-level calculations like the addition of row or column elements.

To calculate the maximum element among each column, the minimum element
among each row, and the addition of all the row elements, consider the following
example.

Example
1. import numpy as np
2. a = np.array([[1,2,30],[10,15,4]])
3. print("The array:",a)
4. print("The maximum elements of columns:",a.max(axis = 0))
5. print("The minimum element of rows",a.min(axis = 1))
6. print("The sum of all rows",a.sum(axis = 1))

Output:

The array: [[1 2


30]
[10 15 4]]
The maximum elements of columns: [10 15 30]

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
The minimum element of rows [1 4]
The sum of all rows [33 29]

Finding square root and standard deviation


The sqrt() and std() functions associated with the numpy array are used to find the
square root and standard deviation of the array elements respectively.

Standard deviation means how much each element of the array varies from the
mean value of the numpy array.

Consider the following example.

Example
1. import numpy as np
2. a = np.array([[1,2,30],[10,15,4]])
3. print(np.sqrt(a))
4. print(np.std(a))

Output:

[[1. 1.41421356 5.47722558]


[3.16227766 3.87298335 2. ]]
10.044346115546242

Arithmetic operations on the array


The numpy module allows us to perform the arithmetic operations on multi-
dimensional arrays directly.

In the following example, the arithmetic operations are performed on the two multi-
dimensional arrays a and b.

Example
1. import numpy as np
2. a = np.array([[1,2,30],[10,15,4]])
3. b = np.array([[1,2,3],[12, 19, 29]])
4. print("Sum of array a and b\n",a+b)
5. print("Product of array a and b\n",a*b)
6. print("Division of array a and b\n",a/b)

Array Concatenation
The numpy provides us with the vertical stacking and horizontal stacking which
allows us to concatenate two multi-dimensional arrays vertically or horizontally.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Consider the following example.

Example
1. import numpy as np
2. a = np.array([[1,2,30],[10,15,4]])
3. b = np.array([[1,2,3],[12, 19, 29]])
4. print("Arrays vertically concatenated\n",np.vstack((a,b)));
5. print("Arrays horizontally concatenated\n",np.hstack((a,b)))

Output:

Arrays vertically concatenated


[[ 1 2 30]
[10 15 4]
[ 1 2 3]
[12 19 29]]
Arrays horizontally concatenated
[[ 1 2 30 1 2 3]
[10 15 4 12 19 29]]

NumPy Datatypes
The NumPy provides a higher range of numeric data types than that provided by the
Python. A list of numeric data types is given in the following table.

SN Data type Description

1 bool_ It represents the boolean value indicating true or false. It is stored as

2 int_ It is the default type of integer. It is identical to long type in C that co

3 intc It is similar to the C integer (c int) as it represents 32 or 64-bit int.

4 intp It represents the integers which are used for indexing.

5 int8 It is the 8-bit integer identical to a byte. The range of the value is -12

6 int16 It is the 2-byte (16-bit) integer. The range is -32768 to 32767.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
7 int32 It is the 4-byte (32-bit) integer. The range is -2147483648 to 214748

8 int64 It is the 8-byte (64-bit) integer. The range is -9223372036854775808

9 uint8 It is the 1-byte (8-bit) unsigned integer.

10 uint16 It is the 2-byte (16-bit) unsigned integer.

11 uint32 It is the 4-byte (32-bit) unsigned integer.

12 uint64 It is the 8 bytes (64-bit) unsigned integer.

13 float_ It is identical to float64.

14 float16 It is the half-precision float. 5 bits are reserved for the exponent. 10 b
for the sign.

15 float32 It is a single precision float. 8 bits are reserved for the exponent, 23 b
for the sign.

16 float64 It is the double precision float. 11 bits are reserved for the exponent,
sign.

17 complex_ It is identical to complex128.

18 complex64 It is used to represent the complex number where real and imaginary

19 complex128 It is used to represent the complex number where real and imaginary

NumPy dtype
All the items of a numpy array are data type objects also known as numpy dtypes. A
data type object implements the fixed size of memory corresponding to an array.

We can create a dtype object by using the following syntax.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
1. numpy.dtype(object, align, copy)

The constructor accepts the following object.

Object: It represents the object which is to be converted to the data type.

Align: It can be set to any boolean value. If true, then it adds extra padding to
make it equivalent to a C struct.

Copy: It creates another copy of the dtype object.

Example 1
1. import numpy as np
2. d = np.dtype(np.int32)
3. print(d)

Output:

int32

Example 2
1. import numpy as np
2. d = np.int32(i4)
3. print(d)

Output:

int32

Creating a Structured data type


We can create a map-like (dictionary) data type which contains the mapping
between the values. For example, it can contain the mapping between employees
and salaries or the students and the age, etc.

Consider the following example.

Example 1
1. import numpy as np
2. d = np.dtype([('salary',np.float)])
3. print(d)

Output:

[('salary', '<="" pre="">

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Example 2
1. import numpy as np
2. d=np.dtype([('salary',np.float)])
3. arr = np.array([(10000.12,),(20000.50,)],dtype=d)
4. print(arr['salary'])

Output:

[(10000.12,) (20000.5 ,)]

Numpy Array Creation


The ndarray object can be constructed by using the following routines.

Numpy.empty
As the name specifies, The empty routine is used to create an uninitialized array of
specified shape and data type.

The syntax is given below.

1. numpy.empty(shape, dtype = float, order = 'C')

It accepts the following parameters.

o Shape: The desired shape of the specified array.

o dtype: The data type of the array items. The default is the float.

o Order: The default order is the c-style row-major order. It can be set to F for
FORTRAN-style column-major order.

Example
1. import numpy as np
2. arr = np.empty((3,2), dtype = int)
3. print(arr)

Output:

[[ 140482883954664 36917984]
[ 140482883954648 140482883954648]
[6497921830368665435 172026472699604272]]

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
NumPy.Zeros
This routine is used to create the numpy array with the specified shape where each
numpy array item is initialized to 0.

The syntax is given below.

1. numpy.zeros(shape, dtype = float, order = 'C')

It accepts the following parameters.

o Shape: The desired shape of the specified array.

o dtype: The data type of the array items. The default is the float.

o Order: The default order is the c-style row-major order. It can be set to F for
FORTRAN-style column-major order.

Example
1. import numpy as np
2. arr = np.zeros((3,2), dtype = int)
3. print(arr)

Output:

[[0 0]
[0 0]
[0 0]]

NumPy.ones
This routine is used to create the numpy array with the specified shape where each
numpy array item is initialized to 1.

The syntax to use this module is given below.

1. numpy.ones(shape, dtype = none, order = 'C')

It accepts the following parameters.

o Shape: The desired shape of the specified array.

o dtype: The data type of the array items.

o Order: The default order is the c-style row-major order. It can be set to F for
FORTRAN-style column-major order.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Example
1. import numpy as np
2. arr = np.ones((3,2), dtype = int)
3. print(arr)

Output:

[[1 1]
[1 1]
[1 1]]

Numpy array from existing data


NumPy provides us the way to create an array by using the existing data.

numpy.asarray
This routine is used to create an array by using the existing data in the form of lists,
or tuples. This routine is useful in the scenario where we need to convert a python
sequence into the numpy array object.

The syntax to use the asarray() routine is given below.

1. numpy.asarray(sequence, dtype = None, order = None)

It accepts the following parameters.

1. sequence: It is the python sequence which is to be converted into the


python array.

2. dtype: It is the data type of each item of the array.

3. order: It can be set to C or F. The default is C.

Example: creating numpy array using the list


1. import numpy as np
2. l=[1,2,3,4,5,6,7]
3. a = np.asarray(l);
4. print(type(a))
5. print(a)

Output:

<class 'numpy.ndarray'>

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
[1 2 3 4 5 6 7]

Example: creating a numpy array using Tuple


1. import numpy as np
2. l=(1,2,3,4,5,6,7)
3. a = np.asarray(l);
4. print(type(a))
5. print(a)

Output:

<class 'numpy.ndarray'>
[1 2 3 4 5 6 7]

Example: creating a numpy array using more than one list


1. import numpy as np
2. l=[[1,2,3,4,5,6,7],[8,9]]
3. a = np.asarray(l);
4. print(type(a))
5. print(a)

Output:

<class 'numpy.ndarray'>
[list([1, 2, 3, 4, 5, 6, 7]) list([8, 9])]

numpy.frombuffer
This function is used to create an array by using the specified buffer. The syntax to
use this buffer is given below.

1. numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)

It accepts the following parameters.

o buffer: It represents an object that exposes a buffer interface.

o dtype: It represents the data type of the returned data type array. The
default value is 0.

o count: It represents the length of the returned ndarray. The default value is -
1.

o offset: It represents the starting position to read from. The default value is
0.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Example
1. import numpy as np
2. l = b'hello world'
3. print(type(l))
4. a = np.frombuffer(l, dtype = "S1")
5. print(a)
6. print(type(a))

Output:

<class 'bytes'>
[b'h' b'e' b'l' b'l' b'o' b' ' b'w' b'o' b'r' b'l' b'd']
<class 'numpy.ndarray'>

numpy.fromiter
This routine is used to create a ndarray by using an iterable object. It returns a one-
dimensional ndarray object.

The syntax is given below.

1. numpy.fromiter(iterable, dtype, count = - 1)

It accepts the following parameters.

1. Iterable: It represents an iterable object.

2. dtype: It represents the data type of the resultant array items.

3. count: It represents the number of items to read from the buffer in the
array.

Example
1. import numpy as np
2. list = [0,2,4,6]
3. it = iter(list)
4. x = np.fromiter(it, dtype = float)
5. print(x)
6. print(type(x))

Output:

[0. 2. 4. 6.]
<class 'numpy.ndarray'>

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Numpy Arrays within the numerical range
This section of the tutorial illustrates how the numpy arrays can be created using
some given specified range.

Numpy.arrange
It creates an array by using the evenly spaced values over the given interval. The
syntax to use the function is given below.

1. numpy.arrange(start, stop, step, dtype)

It accepts the following parameters.

1. start: The starting of an interval. The default is 0.

2. stop: represents the value at which the interval ends excluding this value.

3. step: The number by which the interval values change.

4. dtype: the data type of the numpy array items.

group

Example
1. import numpy as np
2. arr = np.arange(0,10,2,float)
3. print(arr)

Output:

[0. 2. 4. 6. 8.]

Example
1. import numpy as np
2. arr = np.arange(10,100,5,int)
3. print("The array over the given range is ",arr)

Output:

The array over the given range is [10 15 20 25 30 35 40 45 50 55 60 65 70


75 80 85 90 95]

NumPy.linspace

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
It is similar to the arrange function. However, it doesn?t allow us to specify the step
size in the syntax.

Instead of that, it only returns evenly separated values over a specified period. The
system implicitly calculates the step size.

The syntax is given below.

1. numpy.linspace(start, stop, num, endpoint, retstep, dtype)

It accepts the following parameters.

1. start: It represents the starting value of the interval.

2. stop: It represents the stopping value of the interval.

3. num: The amount of evenly spaced samples over the interval to be


generated. The default is 50.

4. endpoint: Its true value indicates that the stopping value is included in the
interval.

5. rettstep: This has to be a boolean value. Represents the steps and samples
between the consecutive numbers.

6. dtype: It represents the data type of the array items.

Example
1. import numpy as np
2. arr = np.linspace(10, 20, 5)
3. print("The array over the given range is ",arr)

Output:

The array over the given range is [10. 12.5 15. 17.5 20.]

Example
1. import numpy as np
2. arr = np.linspace(10, 20, 5, endpoint = False)
3. print("The array over the given range is ",arr)

Output:

The array over the given range is [10. 12. 14. 16. 18.]

numpy.logspace
It creates an array by using the numbers that are evenly separated on a log scale.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
The syntax is given below.

1. numpy.logspace(start, stop, num, endpoint, base, dtype)

It accepts the following parameters.

1. start: It represents the starting value of the interval in the base.

2. stop: It represents the stopping value of the interval in the base.

3. num: The number of values between the range.

4. endpoint: It is a boolean type value. It makes the value represented by stop


as the last value of the interval.

5. base: It represents the base of the log space.

6. dtype: It represents the data type of the array items.

Example
1. import numpy as np
2. arr = np.logspace(10, 20, num = 5, endpoint = True)
3. print("The array over the given range is ",arr)

Output:

The array over the given range is [1.00000000e+10 3.16227766e+12


1.00000000e+15 3.16227766e+17
1.00000000e+20]

Example
1. import numpy as np
2. arr = np.logspace(10, 20, num = 5,base = 2, endpoint = True)
3. print("The array over the given range is ",arr)

Output:

The array over the given range is [1.02400000e+03 5.79261875e+03


3.27680000e+04 1.85363800e+05
1.04857600e+06]

NumPy Broadcasting
In Mathematical operations, we may need to consider the arrays of different shapes.
NumPy can perform such operations where the array of different shapes are
involved.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
For example, if we consider the matrix multiplication operation, if the shape of the
two matrices is the same then this operation will be easily performed. However, we
may also need to operate if the shape is not similar.

Consider the following example to multiply two arrays.

Example
1. import numpy as np
2. a = np.array([1,2,3,4,5,6,7])
3. b = np.array([2,4,6,8,10,12,14])
4. c = a*b;
5. print(c)

Output:

[ 2 8 18 32 50 72 98]

However, in the above example, if we consider arrays of different shapes, we will get
the errors as shown below.

Example
1. import numpy as np
2. a = np.array([1,2,3,4,5,6,7])
3. b = np.array([2,4,6,8,10,12,14,19])
4. c = a*b;
5. print(c)

Output:

ValueError: operands could not be broadcast together with shapes (7,) (8,)

In the above example, we can see that the shapes of the two arrays are not similar
and therefore they cannot be multiplied together. NumPy can perform such
operation by using the concept of broadcasting.

In broadcasting, the smaller array is broadcast to the larger array to make their
shapes compatible with each other.

Broadcasting Rules
Broadcasting is possible if the following cases are satisfied.

1. The smaller dimension array can be appended with '1' in its shape.

2. Size of each output dimension is the maximum of the input sizes in the
dimension.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
3. An input can be used in the calculation if its size in a particular dimension
matches the output size or its value is exactly 1.

4. If the input size is 1, then the first data entry is used for the calculation along
the dimension.

Broadcasting can be applied to the arrays if the following rules are satisfied.

1. All the input arrays have the same shape.

2. Arrays have the same number of dimensions, and the length of each
dimension is either a common length or 1.

3. Array with the fewer dimension can be appended with '1' in its shape.

Let's see an example of broadcasting.

Example
1. import numpy as np
2. a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
3. b = np.array([2,4,6,8])
4. print("\nprinting array a..")
5. print(a)
6. print("\nprinting array b..")
7. print(b)
8. print("\nAdding arrays a and b ..")
9. c = a + b;
10. print(c)

Output:

printing array a..


[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]

printing array b..


[2 4 6 8]

Adding arrays a and b ..


[[ 3 6 9 12]
[ 4 8 11 14]
[12 24 45 11]]

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
NumPy Array Iteration
NumPy provides an iterator object, i.e., nditer which can be used to iterate over the
given array using python standard Iterator interface.

Consider the following example.

Example
1. import numpy as np
2. a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
3. print("Printing array:")
4. print(a);
5. print("Iterating over the array:")
6. for x in np.nditer(a):
7. print(x,end=' ')

Output:

Printing array:
[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]
Iterating over the array:
1 2 3 4 2 4 5 6 10 20 39 3

Order of the iteration doesn't follow any special ordering like row-major or column-
order. However, it is intended to match the memory layout of the array.

Let's iterate over the transpose of the array given in the above example.

Example
1. import numpy as np
2. a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
3. print("Printing the array:")
4. print(a)
5. print("Printing the transpose of the array:")
6. at = a.T
7. print(at)
8.
9. #this will be same as previous
10. for x in np.nditer(at):
11. print(print("Iterating over the array:")
12. for x in np.nditer(a):
13. print(x,end=' ')

Output:

Printing the array:


[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]
Printing the transpose of the array:
[[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]
1 2 3 4 2 4 5 6 10 20 39 3

Order of Iteration
As we know, there are two ways of storing values into the numpy arrays:

1. F-style order

2. C-style order

Let's see an example of how the numpy Iterator treats the specific orders (F or C).

Example
1. import numpy as np
2.
3. a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
4.
5. print("\nPrinting the array:\n")
6.
7. print(a)
8.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
9. print("\nPrinting the transpose of the array:\n")
10. at = a.T
11.
12. print(at)
13.
14. print("\nIterating over the transposed array\n")
15.
16. for x in np.nditer(at):
17. print(x, end= ' ')
18.
19. print("\nSorting the transposed array in C-style:\n")
20.
21. c = at.copy(order = 'C')
22.
23. print(c)
24.
25. print("\nIterating over the C-style array:\n")
26. for x in np.nditer(c):
27. print(x,end=' ')
28.
29.
30. d = at.copy(order = 'F')
31.
32. print(d)
33. print("Iterating over the F-style array:\n")
34. for x in np.nditer(d):
35. print(x,end=' ')

Output:

Printing the array:

[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]

Printing the transpose of the array:

[[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Iterating over the transposed array

1 2 3 4 2 4 5 6 10 20 39 3
Sorting the transposed array in C-style:

[[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]

Iterating over the C-style array:

1 2 10 2 4 20 3 5 39 4 6 3 [[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]
Iterating over the F-style array:

1 2 3 4 2 4 5 6 10 20 39 3

We can mention the order 'C' or 'F' while defining the Iterator object itself. Consider
the following example.

Example
1. import numpy as np
2.
3. a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
4.
5. print("\nPrinting the array:\n")
6.
7. print(a)
8.
9. print("\nPrinting the transpose of the array:\n")
10. at = a.T
11.
12. print(at)
13.
14. print("\nIterating over the transposed array\n")
15.
16. for x in np.nditer(at):
17. print(x, end= ' ')
18.
19. print("\nSorting the transposed array in C-style:\n")
20.
21. print("\nIterating over the C-style array:\n")

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
22. for x in np.nditer(at, order = 'C'):
23. print(x,end=' ')

Output:

Iterating over the transposed array

1 2 3 4 2 4 5 6 10 20 39 3
Sorting the transposed array in C-style:

Iterating over the C-style array:

1 2 10 2 4 20 3 5 39 4 6 3

Array Values Modification


We can not modify the array elements during the iteration since the op-flag
associated with the Iterator object is set to readonly.

However, we can set this flag to readwrite or write only to modify the array values.
Consider the following example.

Example
1. import numpy as np
2.
3. a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
4.
5. print("\nPrinting the original array:\n")
6.
7. print(a)
8.
9. print("\nIterating over the modified array\n")
10.
11. for x in np.nditer(a, op_flags = ['readwrite']):
12. x[...] = 3 * x;
13. print(x,end = ' ')

Output:

Printing the original array:

[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]

Iterating over the modified array

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
3 6 9 12 6 12 15 18 30 60 117 9

NumPy Bitwise Operators


Numpy provides the following bitwise operators.

SN Operator Description

1 bitwise_and It is used to calculate the bitwise and operation between the corr

2 bitwise_or It is used to calculate the bitwise or operation between the corres

3 invert It is used to calculate the bitwise not the operation of the array e

4 left_shift It is used to shift the bits of the binary representation of the elem

5 right_shift It is used to shift the bits of the binary representation of the elem

bitwise_and Operation
The NumPy provides the bitwise_and() function which is used to calculate the
bitwise_and operation of the two operands.

The bitwise and operation is performed on the corresponding bits of the binary
representation of the operands. If both the corresponding bit in the operands is set
to 1, then only the resultant bit in the AND result will be set to 1 otherwise it will be
set to 0.

Example
1. import numpy as np
2.
3. a = 10
4. b = 12
5.
6. print("binary representation of a:",bin(a))
7. print("binary representation of b:",bin(b))

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
8. print("Bitwise-and of a and b: ",np.bitwise_and(a,b))

Output:

binary representation of a: 0b1010


binary representation of b: 0b1100
Bitwise-and of a and b: 8

AND Truth Table


The output of the AND result of the two bits is 1 if and only if both the bits are 1
otherwise it will be 0.

A B AND (A, B)

0 0 0

0 1 0

1 0 0

1 1 1

bitwise_or Operator
The NumPy provides the bitwise_or() function which is used to calculate the bitwise
or operation of the two operands.

The bitwise or operation is performed on the corresponding bits of the binary


representation of the operands. If one of the corresponding bit in the operands is set
to 1 then the resultant bit in the OR result will be set to 1; otherwise it will be set to
0.

Example
1. import numpy as np
2.
3. a = 50
4. b = 90
5. print("binary representation of a:",bin(a))
6. print("binary representation of b:",bin(b))
7. print("Bitwise-or of a and b: ",np.bitwise_or(a,b))

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Output:

binary representation of a: 0b110010


binary representation of b: 0b1011010
Bitwise-or of a and b: 122

Or truth table
The output of the OR result of the two bits is 1 if one of the bits are 1 otherwise it
will be 0.

A B Or (A, B)

0 0 0

0 1 1

1 0 1

1 1 1

Invert operation
It is used to calculate the bitwise not the operation of the given operand. The 2's
complement is returned if the signed integer is passed in the function.

Consider the following example.

Example
1. import numpy as np
2.
3. arr = np.array([20],dtype = np.uint8)
4. print("Binary representation:",np.binary_repr(20,8))
5.
6. print(np.invert(arr))
7.
8. print("Binary representation: ", np.binary_repr(235,8))

Output:

Binary representation: 00010100

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
[235]
Binary representation: 11101011

It shifts the bits in the binary representation of the operand to the left by the
specified position. An equal number of 0s are appended from the right. Consider the
following example.

Example
1. import numpy as np
2.
3. print("left shift of 20 by 3 bits",np.left_shift(20, 3))
4.
5. print("Binary representation of 20 in 8 bits",np.binary_repr(20, 8))
6.
7. print("Binary representation of 160 in 8 bits",np.binary_repr(160,8))

Output:

left shift of 20 by 3 bits 160


Binary representation of 20 in 8 bits 00010100
Binary representation of 160 in 8 bits 10100000

Right Shift Operation


It shifts the bits in the binary representation of the operand to the right by the
specified position. An equal number of 0s are appended from the left. Consider the
following example.

Example
1. import numpy as np
2.
3. print("left shift of 20 by 3 bits",np.right_shift(20, 3))
4.
5. print("Binary representation of 20 in 8 bits",np.binary_repr(20, 8))
6.
7. print("Binary representation of 160 in 8 bits",np.binary_repr(160,8))

Output:

left shift of 20 by 3 bits 2


Binary representation of 20 in 8 bits 00010100
Binary representation of 160 in 8 bits 10100000

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
NumPy Mathematical Functions
Numpy contains a large number of mathematical functions which can be used to
perform various mathematical operations. The mathematical functions include
trigonometric functions, arithmetic functions, and functions for handling complex
numbers. Let's discuss the mathematical functions.

Trigonometric functions
Numpy contains the trigonometric functions which are used to calculate the sine,
cosine, and tangent of the different angles in radian.

The sin, cos, and tan functions return the trigonometric ratio for the specified
angles. Consider the following example.

Example
1. import numpy as np
2. arr = np.array([0, 30, 60, 90, 120, 150, 180])
3. print("\nThe sin value of the angles",end = " ")
4. print(np.sin(arr * np.pi/180))
5. print("\nThe cosine value of the angles",end = " ")
6. print(np.cos(arr * np.pi/180))
7. print("\nThe tangent value of the angles",end = " ")
8. print(np.tan(arr * np.pi/180))

Output:

The sin value of the angles


[0.00000000e+00 5.00000000e-01 8.66025404e-01 1.00000000e+00
8.66025404e-01 5.00000000e-01 1.22464680e-16]

The cosine value of the angles


[ 1.00000000e+00 8.66025404e-01 5.00000000e-01 6.12323400e-17
-5.00000000e-01 -8.66025404e-01 -1.00000000e+00]

The tangent value of the angles [ 0.00000000e+00 5.77350269e-01


1.73205081e+00 1.63312394e+16
-1.73205081e+00 -5.77350269e-01 -1.22464680e-16]

On the other hand, arcsin(), arccos(), and arctan() functions return the
trigonometric inverse of the specified angles.

The numpy.degrees() function can be used to verify the result of these trigonometric
functions. Consider the following example.

Example
1. import numpy as np

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
2. arr = np.array([0, 30, 60, 90])
3. print("printing the sin values of different angles")
4.
5. sinval = np.sin(arr*np.pi/180)
6.
7. print(sinval)
8. print("printing the inverse of the sin")
9. cosec = np.arcsin(sinval)
10.
11. print(cosec)
12.
13. print("printing the values in degrees")
14. print(np.degrees(cosec))
15.
16. print("\nprinting the cos values of different angles")
17. cosval = np.cos(arr*np.pi/180)
18.
19. print(cosval)
20. print("printing the inverse of the cos")
21. sec = np.arccos(cosval)
22. print(sec)
23.
24. print("\nprinting the values in degrees")
25. print(np.degrees(sec))
26.
27. print("\nprinting the tan values of different angles")
28. tanval = np.tan(arr*np.pi/180)
29.
30. print(tanval)
31. print("printing the inverse of the tan")
32. cot = np.arctan(tanval)
33. print(cot)
34.
35. print("\nprinting the values in degrees")
36. print(np.degrees(cot))

Output:

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
printing the sin values of different angles
[0. 0.5 0.8660254 1. ]
printing the inverse of the sin
[0. 0.52359878 1.04719755 1.57079633]
printing the values in degrees
[ 0. 30. 60. 90.]

printing the cos values of different angles


[1.00000000e+00 8.66025404e-01 5.00000000e-01 6.12323400e-17]
printing the inverse of the cos
[0. 0.52359878 1.04719755 1.57079633]

printing the values in degrees


[ 0. 30. 60. 90.]

printing the tan values of different angles


[0.00000000e+00 5.77350269e-01 1.73205081e+00 1.63312394e+16]
printing the inverse of the tan
[0. 0.52359878 1.04719755 1.57079633]

printing the values in degrees


[ 0. 30. 60. 90.]

Rounding Functions
The numpy provides various functions that can be used to truncate the value of a
decimal float number rounded to a particular precision of decimal numbers. Let's
discuss the rounding functions.

The numpy.around() function


This function returns a decimal value rounded to a desired position of the decimal.
The syntax of the function is given below.

1. numpy.around(num, decimals)

It accepts the following parameters.

SN Parameter Description

1 num It is the input number.

2 decimals It is the number of decimals which to which the number is to be rounded.


the decimal will be moved to the left.

Consider the following example.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Example
1. import numpy as np
2. arr = np.array([12.202, 90.23120, 123.020, 23.202])
3. print("printing the original array values:",end = " ")
4. print(arr)
5. print("Array values rounded off to 2 decimal position",np.around(arr, 2))
6. print("Array values rounded off to -1 decimal position",np.around(arr, -1))

Output:

printing the original array values: [ 12.202 90.2312 123.02 23.202 ]


Array values rounded off to 2 decimal position [ 12.2 90.23 123.02 23.2
]
Array values rounded off to -2 decimal position [ 10. 90. 120. 20.]

The numpy.floor() function


This function is used to return the floor value of the input data which is the largest
integer not greater than the input value. Consider the following example.

Example
1. import numpy as np
2. arr = np.array([12.202, 90.23120, 123.020, 23.202])
3. print(np.floor(arr))

Output:

[ 12. 90. 123. 23.]

The numpy.ceil() function


This function is used to return the ceiling value of the array values which is the
smallest integer value greater than the array element. Consider the following
example.

Example
1. import numpy as np
2. arr = np.array([12.202, 90.23120, 123.020, 23.202])
3. print(np.ceil(arr))

Output:

[ 13. 91. 124. 24.]

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Next →← Prev

Numpy statistical functions


Numpy provides various statistical functions which are used to perform some
statistical data analysis. In this section of the tutorial, we will discuss the
statistical functions provided by the numpy.

Finding the minimum and maximum elements from


the array
The numpy.amin() and numpy.amax() functions are used to find the minimum
and maximum of the array elements along the specified axis respectively.

Consider the following example.

Example
1. import numpy as np
2.
3. a = np.array([[2,10,20],[80,43,31],[22,43,10]])
4.
5. print("The original array:\n")
6. print(a)
7.
8.
9. print("\nThe minimum element among the array:",np.amin(a))
10. print("The maximum element among the array:",np.amax(a))
11.
12. print("\nThe minimum element among the rows of array",np.amin(a,0))
13. print("The maximum element among the rows of array",np.amax(a,0))
14.
15. print("\nThe minimum element among the columns of array",np.amin(a,1)
)
16. print("The maximum element among the columns of array",np.amax(a,1))

Output:

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
The original array:

[[ 2 10 20]
[80 43 31]
[22 43 10]]

The minimum element among the array: 2


The maximum element among the array: 80

The minimum element among the rows of array [ 2 10 10]


The maximum element among the rows of array [80 43 31]

The minimum element among the columns of array [ 2 31 10]


The maximum element among the columns of array [20 80 43]

numpy.ptp() function
The name of the function numpy.ptp() is derived from the name peak-to-peak. It
is used to return the range of values along an axis. Consider the following
example.

Example
1. import numpy as np
2.
3. a = np.array([[2,10,20],[80,43,31],[22,43,10]])
4.
5. print("Original array:\n",a)
6.
7. print("\nptp value along axis 1:",np.ptp(a,1))
8.
9. print("ptp value along axis 0:",np.ptp(a,0))

Output:

Original array:
[[ 2 10 20]
[80 43 31]
[22 43 10]]

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
ptp value along axis 1: [18 49 33]
ptp value along axis 0: [78 33 21]

numpy.percentile() function
The syntax to use the function is given below.

1. numpy.percentile(input, q, axis)

It accepts the following parameters.

1. input: It is the input array.

2. q: It is the percentile (1-100) which is calculated of the array element.

3. axis: It is the axis along which the percentile is to be calculated.

Consider the following example.

Example
1. import numpy as np
2.
3. a = np.array([[2,10,20],[80,43,31],[22,43,10]])
4.
5. print("Array:\n",a)
6.
7. print("\nPercentile along axis 0",np.percentile(a, 10,0))
8.
9. print("Percentile along axis 1",np.percentile(a, 10, 1))

Output:

Array:
[[ 2 10 20]
[80 43 31]
[22 43 10]]

Percentile along axis 0 [ 6. 16.6 12. ]


Percentile along axis 1 [ 3.6 33.4 12.4]

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Calculating median, mean, and average of array
items
The numpy.median() function:
Median is defined as the value that is used to separate the higher range of data
sample with a lower range of data sample. The function numpy.median() is used
to calculate the median of the multi-dimensional or one-dimensional arrays.

The numpy.mean() function:


The mean can be calculated by adding all the items of the arrays dividing by the
number of array elements. We can also mention the axis along which the mean
can be calculated.

The numpy.average() function:


The numpy.average() function is used to find the weighted average along the axis
of the multi-dimensional arrays where their weights are given in another array.

Consider the following example.

Example
1. import numpy as np
2.
3. a = np.array([[1,2,3],[4,5,6],[7,8,9]])
4.
5. print("Array:\n",a)
6.
7. print("\nMedian of array along axis 0:",np.median(a,0))
8. print("Mean of array along axis 0:",np.mean(a,0))
9. print("Average of array along axis 1:",np.average(a,1))

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
NumPy Sorting and Searching
Numpy provides a variety of functions for sorting and searching. There are various
sorting algorithms like quicksort, merge sort and heapsort which is implemented
using the numpy.sort() function.

The kind of the sorting algorithm to be used in the sort operation must be
mentioned in the function call.

Let's discuss the sorting algorithm which is implemented in numpy.sort()

SN Algorithm Worst case complexity

1 Quick Sort O (n ^ 2)

2 Merge Sort O (n * log(n))

3 Heap Sort O (n * log(n))

The syntax to use the numpy.sort() function is given below.

1. numpy.sort(a, axis, kind, order)

It accepts the following parameters.

SN Parameter Description

1 input It represents the input array which is to be sorted.

2 axis It represents the axis along which the array is to be sorted. If the axis is n
available axis.

3 kind It represents the type of sorting algorithm which is to be used while sortin

4 order It represents the filed according to which the array is to be sorted in the ca

Consider the following example.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Example
1. import numpy as np
2.
3. a = np.array([[10,2,3],[4,5,6],[7,8,9]])
4.
5. print("Sorting along the columns:")
6. print(np.sort(a))
7.
8. print("Sorting along the rows:")
9. print(np.sort(a, 0))
10.
11. data_type = np.dtype([('name', 'S10'),('marks',int)])
12.
13. arr = np.array([('Mukesh',200),('John',251)],dtype = data_type)
14.
15. print("Sorting data ordered by name")
16.
17. print(np.sort(arr,order = 'name'))

Output:

Sorting along the columns:


[[ 2 3 10]
[ 4 5 6]
[ 7 8 9]]
Sorting along the rows:
[[ 4 2 3]
[ 7 5 6]
[10 8 9]]
Sorting data ordered by name
[(b'John', 251) (b'Mukesh', 200)]

numpy.argsort() function
This function is used to perform an indirect sort on an input array that is, it returns
an array of indices of data which is used to construct the array of sorted data.

Consider the following example.

Example
1. import numpy as np
2.
3. a = np.array([90, 29, 89, 12])
4.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
5. print("Original array:\n",a)
6.
7. sort_ind = np.argsort(a)
8.
9. print("Printing indices of sorted data\n",sort_ind)
10.
11. sort_a = a[sort_ind]
12.
13. print("printing sorted array")
14.
15. for i in sort_ind:
16. print(a[i],end = " ")

Output:

Original array:
[90 29 89 12]
Printing indices of sorted data
[3 1 2 0]
printing sorted array
12 29 89 90

numpy.lexsort() function
This function is used to sort the array using the sequence of keys indirectly. This
function performs similarly to the numpy.argsort() which returns the array of indices
of sorted data.

Consider the following example.

Example
1. import numpy as np
2.
3. a = np.array(['a','b','c','d','e'])
4.
5. b = np.array([12, 90, 380, 12, 211])
6.
7. ind = np.lexsort((a,b))
8.
9. print("printing indices of sorted data")
10.
11. print(ind)
12.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
13. print("using the indices to sort the array")
14.
15. for i in ind:
16. print(a[i],b[i])

Output:

printing indices of sorted data


[0 3 1 4 2]
using the indices to sort the array
a 12
d 12
b 90
e 211
c 380

numpy.nonzero() function
This function is used to find the location of the non-zero elements from the array.

Consider the following example.

Example
1. import numpy as np
2.
3. b = np.array([12, 90, 380, 12, 211])
4.
5. print("printing original array",b)
6.
7. print("printing location of the non-zero elements")
8.
9. print(b.nonzero())

Output:

printing original array [ 12 90 380 12 211]


printing location of the non-zero elements
(array([0, 1, 2, 3, 4]),)

numpy.where() function
This function is used to return the indices of all the elements which satisfies a
particular condition.

Consider the following example.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Example
1. import numpy as np
2.
3. b = np.array([12, 90, 380, 12, 211])
4.
5. print(np.where(b>12))
6.
7. c = np.array([[20, 24],[21, 23]])
8.
9. print(np.where(c>20))

Output:

(array([1, 2, 4]),)
(array([0, 1, 1]), array([1, 0, 1]))

NumPy Copies and Views


The copy of an input array is physically stored at some other location and the
content stored at that particular location is returned which is the copy of the input
array whereas the different view of the same memory location is returned in the
case of view.

In this section of the tutorial, we will consider the way by which, the different copies
and views are generated from some memory location.

Array Assignment
The assignment of a numpy array to another array doesn't make the direct copy of
the original array, instead, it makes another array with the same content and same
id. It represents the reference to the original array. Changes made on this reference
are also reflected in the original array.

The id() function returns the universal identifier of the array similar to the pointer in
C.

Consider the following example.

Example
1. import numpy as np
2.
3. a = np.array([[1,2,3,4],[9,0,2,3],[1,2,3,19]])

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
4.
5. print("Original Array:\n",a)
6.
7. print("\nID of array a:",id(a))
8.
9. b = a
10.
11. print("\nmaking copy of the array a")
12.
13. print("\nID of b:",id(b))
14.
15. b.shape = 4,3;
16.
17. print("\nChanges on b also reflect to a:")
18. print(a)

Output:

Original Array:
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]

ID of array a: 139663602288640

making copy of the array a

ID of b: 139663602288640

Changes on b also reflect to a:


[[ 1 2 3]
[ 4 9 0]
[ 2 3 1]
[ 2 3 19]]

ndarray.view() method
The ndarray.view() method returns the new array object which contains the same
content as the original array does. Since it is a new array object, changes made on
this object do not reflect the original array.

Consider the following example.

Example
1. import numpy as np
2.
3. a = np.array([[1,2,3,4],[9,0,2,3],[1,2,3,19]])

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
4.
5. print("Original Array:\n",a)
6.
7. print("\nID of array a:",id(a))
8.
9. b = a.view()
10.
11. print("\nID of b:",id(b))
12.
13. print("\nprinting the view b")
14. print(b)
15.
16. b.shape = 4,3;
17.
18. print("\nChanges made to the view b do not reflect a")
19. print("\nOriginal array \n",a)
20. print("\nview\n",b)

Output:

Original Array:
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]

ID of array a: 140280414447456

ID of b: 140280287000656

printing the view b


[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]

Changes made to the view b do not reflect a

Original array
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]

view
[[ 1 2 3]
[ 4 9 0]
[ 2 3 1]
[ 2 3 19]]

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
ndarray.copy() method
It returns the deep copy of the original array which doesn't share any memory with
the original array. The modification made to the deep copy of the original array
doesn't reflect the original array.

Consider the following example.

Example
1. import numpy as np
2.
3. a = np.array([[1,2,3,4],[9,0,2,3],[1,2,3,19]])
4.
5. print("Original Array:\n",a)
6.
7. print("\nID of array a:",id(a))
8.
9. b = a.copy()
10.
11. print("\nID of b:",id(b))
12.
13. print("\nprinting the deep copy b")
14. print(b)
15.
16. b.shape = 4,3;
17.
18. print("\nChanges made to the copy b do not reflect a")
19. print("\nOriginal array \n",a)
20. print("\nCopy\n",b)

Output:

Original Array:
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]

ID of array a: 139895697586176

ID of b: 139895570139296

printing the deep copy b


[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Changes made to the copy b do not reflect a

Original array
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]

Copy
[[ 1 2 3]
[ 4 9 0]
[ 2 3 1]
[ 2 3 19]]

NumPy Matrix Library


NumPy contains a matrix library, i.e. numpy.matlib which is used to configure
matrices instead of ndarray objects.

numpy.matlib.empty() function
This function is used to return a new matrix with the uninitialized entries. The syntax
to use this function is given below.

1. numpy.matlib.empty(shape, dtype, order)

It accepts the following parameter.

1. shape: It is the tuple defining the shape of the matrix.

2. dtype: It is the data type of the matrix.

3. order: It is the insertion order of the matrix, i.e. C or F.

Consider the following example.

Example
1. import numpy as np
2.
3. import numpy.matlib
4.
5. print(numpy.matlib.empty((3,3)))

Output:

[[6.90262230e-310 6.90262230e-310 6.90262304e-310]

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
[6.90262304e-310 6.90261674e-310 6.90261552e-310]
[6.90261326e-310 6.90262311e-310 3.95252517e-322]]

numpy.matlib.zeros() function
This function is used to create the matrix where the entries are initialized to zero.

Consider the following example.

Example
1. import numpy as np
2.
3. import numpy.matlib
4.
5. print(numpy.matlib.zeros((4,3)))

Output:

[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]

numpy.matlib.ones() function
This function returns a matrix with all the elements initialized to 1.

Consider the following example.

Example
1. import numpy as np
2.
3. import numpy.matlib
4.
5. print(numpy.matlib.ones((2,2)))

Output:

[[1. 1.]
[1. 1.]]

numpy.matlib.eye() function
This function returns a matrix with the diagonal elements initialized to 1 and zero
elsewhere. The syntax to use this function is given below.

1. numpy.matlib.eye(n, m, k, dtype)

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
It accepts the following parameters.

1. n: It represents the number of rows in the resulting matrix.

2. m: It represents the number of columns, defaults to n.

3. k: It is the index of diagonal.

4. dtype: It is the data type of the output

Consider the following example.

Example
1. import numpy as np
2.
3. import numpy.matlib
4.
5. print(numpy.matlib.eye(n = 3, M = 3, k = 0, dtype = int))

Output:

[[1 0 0]
[0 1 0]
[0 0 1]]

numpy.matlib.identity() function
This function is used to return an identity matrix of the given size. An identity matrix
is the one with diagonal elements initializes to 1 and all other elements to zero.

Consider the following example.

Example
1. import numpy as np
2.
3. import numpy.matlib
4.
5. print(numpy.matlib.identity(5, dtype = int))

Output:

[[1 0 0 0 0]
[0 1 0 0 0]
[0 0 1 0 0]
[0 0 0 1 0]
[0 0 0 0 1]]

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
numpy.matlib.rand() function
This function is used to generate a matrix where all the entries are initialized with
random values.

Consider the following example.

Example
1. import numpy as np
2.
3. import numpy.matlib
4.
5. print(numpy.matlib.rand(3,3))

Output:

[[0.86201511 0.86980769 0.06704884]


[0.80531086 0.53814098 0.84394673]
[0.85653048 0.8146121 0.35744405]]

NumPy Linear Algebra


Numpy provides the following functions to perform the different algebraic
calculations on the input data.

SN Function Definition

1 dot() It is used to calculate the dot product of two arrays.

2 vdot() It is used to calculate the dot product of two vectors.

3 inner() It is used to calculate the inner product of two arrays.

4 matmul() It is used to calculate the matrix multiplication of two arra

5 det() It is used to calculate the determinant of a matrix.

6 solve() It is used to solve the linear matrix equation.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
7 inv() It is used to calculate the multiplicative inverse of the mat

numpy.dot() function
This function is used to return the dot product of the two matrices. It is similar to
the matrix multiplication. Consider the following example.

Example
1. import numpy as np
2. a = np.array([[100,200],[23,12]])
3. b = np.array([[10,20],[12,21]])
4. dot = np.dot(a,b)
5. print(dot)

Output:

[[3400 6200]
[ 374 712]]

The dot product is calculated as:

[100 * 10 + 200 * 12, 100 * 20 + 200 * 21] [23*10+12*12, 23*20 + 12*21]

numpy.vdot() function
This function is used to calculate the dot product of two vectors. It can be defined as
the sum of the product of corresponding elements of multi-dimensional arrays.

Consider the following example.

Example
1. import numpy as np
2. a = np.array([[100,200],[23,12]])
3. b = np.array([[10,20],[12,21]])
4. vdot = np.vdot(a,b)
5. print(vdot)

Output:

5528

np.vdot(a,b) = 100 *10 + 200 * 20 + 23 * 12 + 12 * 21 = 5528

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
numpy.inner() function
This function returns the sum of the product of inner elements of the one-
dimensional array. For n-dimensional arrays, it returns the sum of the product of
elements over the last axis.

Consider the following example.

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

Output:

130

numpy.matmul() function
It is used to return the multiplication of the two matrices. It gives an error if the
shape of both matrices is not aligned for multiplication. Consider the following
example.

Example
1. import numpy as np
2. a = np.array([[1,2,3],[4,5,6],[7,8,9]])
3. b = np.array([[23,23,12],[2,1,2],[7,8,9]])
4. mul = np.matmul(a,b)
5. print(mul)

numpy determinant
The determinant of the matrix can be calculated using the diagonal elements. The
determinant of following 2 X 2 matrix

A B
C D

can be calculated as AD - BC.

The numpy.linalg.det() function is used to calculate the determinant of the matrix.


Consider the following example.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Example
1. import numpy as np
2. a = np.array([[1,2],[3,4]])
3. print(np.linalg.det(a))

Output:

-2.0000000000000004

numpy.linalg.solve() function
This function is used to solve a quadratic equation where values can be given in the
form of the matrix.

The following linear equations

1. 3X + 2 Y + Z = 10
2. X + Y + Z = 5

can be represented by using three matrices as:

1. 3 2 1
2. 1 1 1
3. X
4. Y
5. Z and
6. 10
7. 5.

The two matrices can be passed into the numpy.solve() function given as follows.

Example
1. import numpy as np
2. a = np.array([[1,2],[3,4]])
3. b = np.array([[1,2],[3,4]])
4. print(np.linalg.solve(a, b))

Output:

[[1. 0.]
[0. 1.]]

numpy.linalg.inv() function
INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
This function is used to calculate the multiplicative inverse of the input matrix.
Consider the following example.

Example
1. import numpy as np
2. a = np.array([[1,2],[3,4]])
3. print("Original array:\n",a)
4. b = np.linalg.inv(a)
5. print("Inverse:\n",b)

Output:

Original array:
[[1 2]
[3 4]]
Inverse:
[[-2. 1. ]
[ 1.5 -0.5]]

NumPy Matrix Multiplication in Python


Multiplication of matrix is an operation which produces a single matrix by taking two
matrices as input and multiplying rows of the first matrix to the column of the
second matrix. Note that we have to ensure that the number of rows in the first
matrix should be equal to the number of columns in the second matrix.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
In Python, the process of matrix multiplication using NumPy is known
as vectorization. The main objective of vectorization is to remove or reduce the for
loops which we were using explicitly. By reducing 'for' loops from programs gives
faster computation. The build-in package NumPy is used for manipulation and array-
processing.

These are three methods through which we can perform numpy matrix
multiplication.

1. First is the use of multiply() function, which perform element-wise


multiplication of the matrix.

2. Second is the use of matmul() function, which performs the matrix product of
two arrays.

3. Last is the use of the dot() function, which performs dot product of two
arrays.

Example 1: Element-wise matrix multiplication


1. import numpy as np
2. array1=np.array([[1,2,3],[4,5,6],[7,8,9]],ndmin=3)

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
3. array2=np.array([[9,8,7],[6,5,4],[3,2,1]],ndmin=3)
4. result=np.multiply(array1,array2)
5. result

In the above code

o We have imported numpy with alias name np.

o We have created an array1 and array2 using numpy.array() function with


dimension 3.

o We have created a variable result and assigned the returned value of


np.multiply() function.

o We have passed both the array array1 and array2 in np.multiply().

o Lastly, we tried to print the value of the result.

In the output, a three-dimensional matrix has been shown whose elements are the
result of the element-wise multiplication of both array1 and array2 elements.

Output:

array([[[ 9, 16, 21],


[24, 25, 24],
[21, 16, 9]]])

Example 2: Matrix product


1. import numpy as np
2. array1=np.array([[1,2,3],[4,5,6],[7,8,9]],ndmin=3)
3. array2=np.array([[9,8,7],[6,5,4],[3,2,1]],ndmin=3)
4. result=np.matmul(array1,array2)
5. result

Output:

array([[[ 30, 24, 18],


[ 84, 69, 54],
[138, 114, 90]]])

In the above code

o We have imported numpy with alias name np.

o We have created array1 and array2 using numpy.array() function with


dimension 3.

o We have created a variable result and assigned the returned value of the
np.matmul() function.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
o We have passed both the array array1 and array2 in np.matmul().

o Lastly, we tried to print the value of the result.

In the output, a three-dimensional matrix has been shown whose elements are the
product of both array1 and array2 elements.

Example 3: Dot product


These are the following specifications for numpy.dot:

o When both a and b are 1-D (one dimensional) arrays-> Inner product of two
vectors (without complex conjugation)

o When both a and b are 2-D (two dimensional) arrays -> Matrix multiplication

o When either a or b is 0-D (also known as a scalar) -> Multiply by using


numpy.multiply(a, b) or a * b.

o When a is an N-D array and b is a 1-D array -> Sum product over the last
axis of a and b.

o When a is an N-D array and b is an M-D array provided that M>=2 -> Sum
product over the last axis of a and the second-to-last axis of b:
Also, dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])

1. import numpy as np
2. array1=np.array([[1,2,3],[4,5,6],[7,8,9]],ndmin=3)
3. array2=np.array([[9,8,7],[6,5,4],[3,2,1]],ndmin=3)
4. result=np.dot(array1,array2)
5. result

In the above code

o We have imported numpy with alias name np.

o We have created array1 and array2 using numpy.array() function with


dimension 3.

o We have created a variable result and assigned the returned value of the
np.dot() function.

o We have passed both the array array1 and array2 in np.dot().

o Lastly, we tried to print the value of the result.

In the output, a three-dimensional matrix has been shown whose elements are the
dot product of both array1 and array2 elements.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Output:

array([[[[ 30, 24, 18]],


[[ 84, 69, 54]],
[[138, 114, 90]]]])

numpy.array() in Python
The homogeneous multidimensional array is the main object of NumPy. It is
basically a table of elements which are all of the same type and indexed by a tuple
of positive integers. The dimensions are called axis in NumPy.

The NumPy's array class is known as ndarray or alias array. The numpy.array is
not the same as the standard Python library class array.array. The array.array
handles only one-dimensional arrays and provides less functionality.

Syntax
1. numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin
=0)
Parameters
There are the following parameters in numpy.array() function.

1) object: array_like

Any object, which exposes an array interface whose __array__ method returns any
nested sequence or an array.

2) dtype : optional data-type

This parameter is used to define the desired parameter for the array element. If we
do not define the data type, then it will determine the type as the minimum type
which will require to hold the object in the sequence. This parameter is used only for
upcasting the array.

3) copy: bool(optional)

If we set copy equals to true, the object is copied else the copy will be made when
an object is a nested sequence, or a copy is needed to satisfy any of the other
requirements such as dtype, order, etc.

4) order : {'K', 'A', 'C', 'F'}, optional

The order parameter specifies the memory layout of the array. When the object is
not an array, the newly created array will be in C order (row head or row-major)

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
unless 'F' is specified. When F is specified, it will be in Fortran order (column head or
column-major). When the object is an array, it holds the following order.

order no copy copy=True

'K' Unchanged F and C order preserved.

'A' Unchanged When the input is F and not C then F order otherwise

'C' C order C order

'F' F order F order

When copy=False or the copy is made for the other reason, the result will be the
same as copy= True with some exceptions for A. The default order is 'K'.

5) subok : bool(optional)

When subok=True, then sub-classes will pass-through; otherwise, the returned


array will force to be a base-class array (default).

6) ndmin : int(optional)

This parameter specifies the minimum number of dimensions which the resulting
array should have. Users can be prepended to the shape as needed to meet this
requirement.

Returns
The numpy.array() method returns an ndarray. The ndarray is an array object which
satisfies the specified requirements.

Example 1: numpy.array()
1. import numpy as np
2. arr=np.array([1,2,3])
3. arr

Output:

array([1, 2, 3])

In the above code

o We have imported numpy with alias name np.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
o We have declared the 'arr' variable and assigned the value returned by
np.array() function.

o In the array() function, we have passed only the elements, not axis.

o Lastly, we have tried to print the value of arr.

In the output, an array has been shown.

Example 2:
1. import numpy as np
2. arr=np.array([1,2.,3.])
3. arr

Output:

array([1., 2., 3.])

In the above code

o We have imported numpy with alias name np.

o We have declared the 'arr' variable and assigned the value returned by
np.array() function.

o In the array() function, we have passed elements of different type such as


integer, float, etc.

o Lastly, we have tried to print the value of arr.

In the output, an array has been displayed containing elements in such type which
require minimum memory to hold the object in the sequence.

Example 3: More than one dimensions


1. import numpy as np
2. arr=np.array([[1,2.,3.],[4.,5.,7]])
3. arr

Output:

array([[1., 2., 3.],


[4., 5., 7.]])

In the above code

o We have imported numpy with alias name np.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
o We have declared the 'arr' variable and assigned the value returned by
np.array() function.

o In the array() function, we have passed the number of elements in different


square brackets.

o Lastly, we have tried to print the value of arr.

In the output, a multi-dimensional array has been shown.

Example 4: Minimum dimensions: 2


1. import numpy as np
2. arr=np.array([1,2.,3.],ndmin=2)
3. arr

Output:

array([[1., 2., 3.]])

In the above code

o We have imported numpy with alias name np.

o We have declared the 'arr' variable and assigned the value returned by
np.array() function.

o In the array() function, we have passed the number of elements in a square


bracket and the dimension to create a ndarray.

o Lastly, we have tried to print the value of arr.

In the output, a two-dimensional array has been shown.

Example 5: Type provided


1. import numpy as np
2. arr=np.array([12,45.,3.],dtype=complex)
3. arr

Output:

array([12.+0.j, 45.+0.j, 3.+0.j])

In the above code

o We have imported numpy with alias name np.

o We have declared the 'arr' variable and assigned the value returned by the
np.array() function.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
o In the array() function, we have passed the elements in the square bracket
and set the dtype to complex.

o Lastly, we have tried to print the value of arr.

In the output, the values of the 'arr' elements have been shown in the form of
complex numbers.

Example 6: Creating an array from sub-classes


1. import numpy as np
2. arr=np.array(np.mat('1 2;3 4'))
3. arr
4. arr=np.array(np.mat('1 2;3 4'),subok=True)
5. arr

Output:

array([[1, 2],
[3, 4]])
matrix([[1, 2],
[3, 4]])

In the above code

o We have imported numpy with alias name np.

o We have declared the 'arr' variable and assigned the value returned by the
np.array() function.

o In the array() function, we have passed the elements in the form of the
matrix using np.mat() function and set the subok=True.

o Lastly, we have tried to print the value of arr.

In the output, a multi-dimensional array has been shown.

numpy.concatenate() in Python
The concatenate() function is a function from the NumPy package. This function
essentially combines NumPy arrays together. This function is basically used for
joining two or more arrays of the same shape along a specified axis. There are the
following things which are essential to keep in mind:

1. NumPy's concatenate() is not like a traditional database join. It is like


stacking NumPy arrays.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
2. This function can operate both vertically and horizontally. This means we can
concatenate arrays together horizontally or vertically.

The concatenate() function is usually written as np.concatenate(), but we can also


write it as numpy.concatenate(). It depends on the way of importing the numpy
package, either import numpy as np or import numpy, respectively.

Syntax
1. numpy.concatenate((a1, a2, ...), axis)
Parameters
1) (a1, a2, ...)

This parameter defines the sequence of arrays. Here, a1, a2, a3 ... are the arrays
which have the same shape, except in the dimension corresponding to the axis.

2) axis : int(optional)

This parameter defines the axis along which the array will be joined. By default, its
value is 0.

Result
It will return a ndarray containing the elements of both the arrays.

Example 1: numpy.concatenate()
1. import numpy as np
2. x=np.array([[1,2],[3,4]])
3. y=np.array([[12,30]])

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
4. z=np.concatenate((x,y))
5. z

In the above code

o We have imported numpy with alias name np.

o We have created an array 'x' using np.array() function.

o Then, we have created another array 'y' using the same np.array() function.

o We have declared the variable 'z' and assigned the returned value of
np.concatenate() function.

o We have passed the array 'x' and 'y' in the function.

o Lastly, we tried to print the value of 'z'.

In the output, values of both the arrays, i.e., 'x' and 'y' shown as per the axis=0.

Output:

array([[ 1, 2],
[ 3, 4],
[12, 30]])

Example 2: numpy.concatenate() with axis=0


1. import numpy as np
2. x=np.array([[1,2],[3,4]])
3. y=np.array([[12,30]])
4. z=np.concatenate((x,y), axis=0)
5. z

Output:

array([[ 1, 2],
[ 3, 4],
[12, 30]])

Example 3: numpy.concatenate() with axis=1


1. import numpy as np
2. x=np.array([[1,2],[3,4]])
3. y=np.array([[12,30]])
4. z=np.concatenate((x,y.T), axis=1)
5. z

Output:

array([[ 1, 2, 12],
[ 3, 4, 30]])

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
In the above example, the '.T' used to change the rows into columns and columns
into rows.

Example 4: numpy.concatenate() with axis=None


1. import numpy as np
2. x=np.array([[1,2],[3,4]])
3. y=np.array([[12,30]])
4. z=np.concatenate((x,y), axis=None)
5. z

Output:

array([ 1, 2, 3, 4, 12, 30])

In the above examples, we have used np.concatenate() function. This function is not
preserved masking of MaskedArray inputs. There is the following way through which
we can concatenate the arrays that can preserve masking of MaskedArray inputs.

Example 5: np.ma.concatenate()
1. import numpy as np
2. x=np.ma.arange(3)
3. y=np.arange(3,6)
4. x[1]=np.ma.masked
5. x
6. y
7. z1=np.concatenate([x,y])
8. z2=np.ma.concatenate([x,y])
9. z1
10. z2

In the above code

o We have imported numpy with alias name np.

o We have created an array 'x' using np.ma.arrange() function.

o Then, we have created another array 'y' using the same np.ma.arrange()
function.

o We have declared the variable 'z1' and assigned the returned value of
np.concatenate() function.

o We have declared variable 'z2' and assigned the returned value of


np.ma.concatenate() function.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
o Lastly, we tried to print the value of 'z1' and 'z2'.

In the output, values of both the arrays 'z1' and 'z2' have preserved the masking of
MaskedArray input.

Output:

masked_array(data=[0, --, 2],


mask=[False, True, False],
fill_value=999999)
array([3, 4, 5])
masked_array(data=[0, 1, 2, 3, 4, 5],
mask=False,
fill_value=999999)
masked_array(data=[0, --, 2, 3, 4, 5],
mask=[False, True, False, False, False, False],
fill_value=999999)

numpy.append() in Python
The numpy.append() function is available in NumPy package. As the name suggests,
append means adding something. The numpy.append() function is used to add or
append new values to an existing numpy array. This function adds the new values at
the end of the array.

The numpy append() function is used to merge two arrays. It returns a new array,
and the original array remains unchanged.

Syntax
1. numpy.append(arr, values, axis=None)
Parameters
There are the following parameters of the append() function:

1) arr: array_like

This is a ndarray. The new values are appended to a copy of this array. This
parameter is required and plays an important role in numpy.append() function.

2) values: array_like

This parameter defines the values which are appended to a copy of a ndarray. One
thing is to be noticed here that these values must be of the correct shape as the
original ndarray, excluding the axis. If the axis is not defined, then the values can be
in any shape and will flatten before use.

3) axis: int(optional)

This parameter defines the axis along which values are appended. When the axis is
not given to them, both ndarray and values are flattened before use.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Returns
This function returns a copy of ndarray with values appended to the axis.

Example 1: np.append()
1. import numpy as np
2. a=np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
3. b=np.array([[11, 21, 31], [42, 52, 62], [73, 83, 93]])
4. c=np.append(a,b)
5. c

Output:

array([ 10, 20, 30, 40, 50, 60, 70, 80, 90, 11, 21, 31, 42, 52, 62,
73, 83,
93])

In the above code

o We have imported numpy with alias name np.

o We have created an array 'a' using np.array() function.

o Then we have created another array 'b' using the same np.array() function.

o We have declared the variable 'c' and assigned the returned value of
np.append() function.

o We have passed the array 'a' and 'b' in the function.

o Lastly, we tried to print the value of arr.

In the output, values of both arrays, i.e., 'a' and 'b', have been shown in the
flattened form, and the original array remained same.

Example 2: np.append({a1,a2,...}, axis=0)


1. import numpy as np
2. a=np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
3. b=np.array([[11, 21, 31], [42, 52, 62], [73, 83, 93]])
4. c=np.append(a,b,axis=0)
5. c

In the above code

o We have imported numpy with alias name np.

o We have created an array 'a' using np.array() function.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
o Then we have created another array 'b' using the same np.array() function.

o We have declared the variable 'c' and assigned the returned value of
np.append() function.

o We have passed the array 'a' and 'b' in the function, and we have also passed
the axis as 0.

o Lastly, we tried to print the value of arr.

In the output, values of both arrays, i.e., 'a' and 'b', have been shown vertically in a
single array, and the original array remained the same.

Output:

array([[ 10, 20, 30],


[ 40, 50, 60],
[ 70, 80, 90],
[11, 21, 31],
[42, 52, 62],
[73, 83, 93]])

Example 3: np.append({a1,a2,...}, axis=1)


1. import numpy as np
2. a=np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
3. b=np.array([[11, 21, 31], [42, 52, 62], [73, 83, 93]])
4. c=np.append(a,b,axis=1)
5. c

Output:

array([[ 10, 20, 30, 11, 21, 31],


[ 40, 50, 60, 42, 52, 62],
[ 70, 80, 90, 73, 83, 93]])

numpy.reshape() in Python
The numpy.reshape() function is available in NumPy package. As the name
suggests, reshape means 'changes in shape'. The numpy.reshape() function helps us
to get a new shape to an array without changing its data.

Sometimes, we need to reshape the data from wide to long. So in this situation, we
have to reshape the array using reshape() function.

Syntax
1. numpy.reshape(arr, new_shape, order='C')
Parameters
There are the following parameters of reshape() function:

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
1) arr: array_like

This is a ndarray. This is the source array which we want to reshape. This parameter
is essential and plays a vital role in numpy.reshape() function.

2) new_shape: int or tuple of ints

The shape in which we want to convert our original array should be compatible with
the original array. If an integer, the result will be a 1-D array of that length. One
shape dimension can be -1. Here, the value is approximated by the length of the
array and the remaining dimensions.

3) order: {'C', 'F', 'A'}, optional

These indexes order parameter plays a crucial role in reshape() function. These
index orders are used to read the elements of source array and place the elements
into the reshaped array using this index order.

1. The index order 'C' means to read/write the elements which are using a C-like
index order where the last axis index is changing fastest, back to the first axis
index changing slowest.

2. The index order 'F' means to read/write the elements which are using the
Fortran-like index order, where the last axis index changing slowest and the
first axis index changing fastest.

3. The 'C' and 'F' order take no amount of the memory layout of the underlying
array and only refer to the order of indexing.

4. The index order 'A' means to read/write the elements in Fortran-like index
order, when arr is contiguous in memory, otherwise use C-like order.

Returns
This function returns a ndarray. It is a new view object if possible; otherwise, it will
be a copy. There is no guarantee of the memory layout of the returned array.

Example 1: C-like index ordering


1. import numpy as np
2. x=np.arange(12)
3. y=np.reshape(x, (4,3))
4. x
5. y

Output:

array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])

In the above code

o We have imported numpy with alias name np.

o We have created an array 'a' using np.arrange() function.

o We have declared the variable 'y' and assigned the returned value of the
np.reshape() function.

o We have passed the array 'x' and the shape in the function.

o Lastly, we tried to print the value of arr.

In the output, the array has been represented as three rows and four columns.

Example 2: Equivalent to C ravel then C reshape


1. import numpy as np
2. x=np.arange(12)
3. y=np.reshape(np.ravel(x),(3,4))
4. x
5. y

The ravel() function is used for creating a contiguous flattened array. A one-
dimensional array that contains the elements of the input, is returned. A copy is
made only when it is needed.

Output:

array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])


array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])

Example 3: Fortran-like index ordering


1. import numpy as np
2. x=np.arange(12)
3. y=np.reshape(x, (4, 3), order='F')
4. x
5. y

Output:

array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])


array([[ 0, 4, 8],
[ 1, 5, 9],
[ 2, 6, 10],

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
[ 3, 7, 11]])

In the above code

o We have imported numpy with alias name np.

o We have created an array 'a' using np.arrange() function.

o We have declared the variable 'y' and assigned the returned value of
np.reshape() function.

o We have passed the array 'x' and the shape and Fortran-like index order in
the function.

o Lastly, we tried to print the value of arr.

In the output, the array has been represented as four rows and three columns.

Example 4: Fortran-like index ordering


1. import numpy as np
2. x=np.arange(12)
3. y=np.reshape(np.ravel(x, order='F'), (4, 3), order='F')
4. x
5. y

Output:

array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])


array([[ 0, 4, 8],
[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11]])

Example 5: The unspecified value is inferred to be 2


1. import numpy as np
2. x=np.arange(12)
3. y=np.reshape(x, (2, -1))
4. x
5. y

In the above code

o We have imported numpy with alias name np.

o We have created an array 'a' using np.arrange() function.

o We have declared the variable 'y' and assigned the returned value of the
np.reshape() function.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
o We have passed the array 'x' and the shape (unspecified value) in the
function.

o Lastly, we tried to print the value of arr.

In the output, the array has been represented as two rows and five columns.

Output:

array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])


array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11]])

numpy.sum() in Python
The numpy.sum() function is available in the NumPy package of Python. This
function is used to compute the sum of all elements, the sum of each row, and the
sum of each column of a given array.

Essentially, this sum ups the elements of an array, takes the elements within a
ndarray, and adds them together. It is also possible to add rows and column
elements of an array. The output will be in the form of an array object.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Syntax
There is the following syntax of numpy.sum() function:

1. numpy.sum(arr, axis=None, dtype=None, out=None, keepdims=<no value>,


initial=<no value>)
Parameters
1) arr: array_like

This is a ndarray. This is the source array whose elements we want to sum. This
parameter is essential and plays a vital role in numpy.sum() function.

2) axis: int or None or tuple of ints(optional)

This parameter defines the axis along which a sum is performed. The default axis is
None, which will sum all the elements of the array. When the axis is negative, it
counts from the last to the first axis. In version 1.7.0, a sum is performed on all axis
specified in the tuple instead of a single axis or all axis as before when an axis is a
tuple of ints.

3) dtype: dtype(optional)

This parameter defines the type of the accumulator and the returned array in which
the elements are summed. By default, the dtype of arr is used unless arr has an
integer dtype of less precision than the default platform integer. In such a case,
when arr is signed, then the platform integer is used, and when arr is unsigned, then
an unsigned integer of the same precision as the platform integer is used.

4) out: ndarray(optional)

This parameter defines the alternative output array in which the result will be
placed. This resulting array must have the same shape as the expected output. The
type of output values will be cast, when necessary.

5) keepdims: bool(option)

This parameter defines a Boolean value. When this parameter is set to True, the axis
which is reduced is left in the result as dimensions with size one. With the help of
this option, the result will be broadcast correctly against the input array. The
keepdims will not be passed to the sum method of sub-classes of a ndarray, when
the default value is passed, but not in case of non-default value. If the sub-class
method does not implement keepdims, then any exception can be raised.

6) initial: scalar

This parameter defines the starting value for the sum.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Returns
This function returns an array of the same shape as arr with the specified axis
removed. When arr is a 0-d array, or when the axis is None, a scalar is returned. A
reference to out is returned, when an array output is specified.

Example 1: numpy.array()
1. import numpy as np
2. a=np.array([0.4,0.5])
3. b=np.sum(a)
4. b

Output:

0.9

In the above code

o We have imported numpy with alias name 'np'.

o We have created an array 'a' using np.array() function.

o We have declared variable 'b' and assigned the returned value of np.sum()
function.

o We have passed the array 'a' in the function.

o Lastly, we tried to print the value of b.

In the output, the sum of all the elements of the array has been shown.

Example 2:
1. import numpy as np
2. a=np.array([0.4,0.5,0.9,6.1])
3. x=np.sum(a, dtype=np.int32)
4. x

Output:

In the above code

o We have imported numpy with alias name 'np'.

o We have created an array 'a' using np.array() function.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
o We have declared variable 'x' and assigned the returned value of np.sum()
function.

o We have passed the array 'a' and data type of int32 in the function.

o Lastly, we tried to print the value of x.

In the output, the sum only of integer numbers, not floating-point values has been
displayed.

Example 3:
1. import numpy as np
2. a=np.array([[1,4],[3,5]])
3. b=np.sum(a)
4. b

In the above code

Output:

13

Example 4:
1. import numpy as np
2. a=np.array([[1,4],[3,5]])
3. b=np.sum(a,axis=0)
4. b

In the above code

o We have imported numpy with alias name np.

o We have created an array 'a' using np.array() function.

o We have declared variable 'b' and assigned the returned value of np.sum()
function.

o We have passed the array 'a' and axis=0 in the function.

o Lastly, we tried to print the value of b.

In the output, the sum of the column elements has been calculated accordingly.

Output:

array([4, 9])

Example 5:
1. import numpy as np

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
2. a=np.array([[1,4],[3,5]])
3. b=np.sum(a,axis=1)
4. b

Output:

array([5, 8])

Example 6:
1. import numpy as np
2. b=np.sum([15], initial=8)
3. b

Output:

23

In the above code

o We have imported numpy with alias name np.

o We have declared variable 'b' and assigned the returned value of np.sum()
function.

o We have passed the number of elements and initial value in the function.

o Lastly, we tried to print the value of b.

In the output, the initial value has been added to the last element in the sequence of
elements and then performed the sum of all the elements.

numpy.random() in Python
The random is a module present in the NumPy library. This module contains the
functions which are used for generating random numbers. This module contains
some simple random data generation methods, some permutation and distribution
functions, and random generator functions.

All the functions in a random module are as follows:

Simple random data


There are the following functions of simple random data:

1) p.random.rand(d0, d1, ..., dn)

This function of random module is used to generate random numbers or values in a


given shape.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Example:

1. import numpy as np
2. a=np.random.rand(5,2)
3. a

Output:

array([[0.74710182, 0.13306399],
[0.01463718, 0.47618842],
[0.98980426, 0.48390004],
[0.58661785, 0.62895758],
[0.38432729, 0.90384119]])

2) np.random.randn(d0, d1, ..., dn)

This function of random module return a sample from the "standard normal"
distribution.

Example:

1. import numpy as np
2. a=np.random.randn(2,2)
3. a

Output:

array([[ 1.43327469, -0.02019121],


[ 1.54626422, 1.05831067]])
b=np.random.randn()
b
-0.3080190768904835

3) np.random.randint(low[, high, size, dtype])

This function of random module is used to generate random integers from


inclusive(low) to exclusive(high).

Example:

1. import numpy as np
2. a=np.random.randint(3, size=10)
3. a

Output:

array([1, 1, 1, 2, 0, 0, 0, 0, 0, 0])

4) np.random.random_integers(low[, high, size])

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
This function of random module is used to generate random integers number of type
np.int between low and high.

Example:

1. import numpy as np
2. a=np.random.random_integers(3)
3. a
4. b=type(np.random.random_integers(3))
5. b
6. c=np.random.random_integers(5, size=(3,2))
7. c

Output:

2
<type 'numpy.int32'>
array([[1, 1],
[2, 5],
[1, 3]])

5) np.random.random_sample([size])

This function of random module is used to generate random floats number in the
half-open interval [0.0, 1.0).

Example:

1. import numpy as np
2. a=np.random.random_sample()
3. a
4. b=type(np.random.random_sample())
5. b
6. c=np.random.random_sample((5,))
7. c

Output:

0.09250360565571492
<type 'float'>
array([0.34665418, 0.47027209, 0.75944969, 0.37991244, 0.14159746])

6) np.random.random([size])

This function of random module is used to generate random floats number in the
half-open interval [0.0, 1.0).

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Example:

1. import numpy as np
2. a=np.random.random()
3. a
4. b=type(np.random.random())
5. b
6. c=np.random.random((5,))
7. c

Output:

0.008786953974334155
<type 'float'>
array([0.05530122, 0.59133394, 0.17258794, 0.6912388 , 0.33412534])

7) np.random.ranf([size])

This function of random module is used to generate random floats number in the
half-open interval [0.0, 1.0).

Example:

1. import numpy as np
2. a=np.random.ranf()
3. a
4. b=type(np.random.ranf())
5. b
6. c=np.random.ranf((5,))
7. c

Output:

0.2907792098474542
<type 'float'>
array([0.34084881, 0.07268237, 0.38161256, 0.46494681, 0.88071377])

8) np.random.sample([size])

This function of random module is used to generate random floats number in the
half-open interval [0.0, 1.0).

Example:

1. import numpy as np
2. a=np.random.sample()

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
3. a
4. b=type(np.random.sample())
5. b
6. c=np.random.sample((5,))
7. c

Output:

0.012298209913766511
<type 'float'>
array([0.71878544, 0.11486169, 0.38189074, 0.14303308, 0.07217287])

9) np.random.choice(a[, size, replace, p])

This function of random module is used to generate random sample from a given 1-
D array.

Example:

1. import numpy as np
2. a=np.random.choice(5,3)
3. a
4. b=np.random.choice(5,3, p=[0.2, 0.1, 0.4, 0.2, 0.1])
5. b

Output:

array([0, 3, 4])
array([2, 2, 2], dtype=int64)

10) np.random.bytes(length)

This function of random module is used to generate random bytes.

Example:

1. import numpy as np
2. a=np.random.bytes(7)
3. a

Output:

'nQ\x08\x83\xf9\xde\x8a'

Permutations

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
There are the following functions of permutations:

1) np.random.shuffle()

This function is used for modifying a sequence in-place by shuffling its contents.

Example:

1. import numpy as np
2. a=np.arange(12)
3. a
4. np.random.shuffle(a)
5. a

Output:

array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])


array([10, 3, 2, 4, 5, 8, 0, 9, 1, 11, 7, 6])

2) np.random.permutation()

This function permute a sequence randomly or return a permuted range.

Example:

1. import numpy as np
2. a=np.random.permutation(12)
3. a

Output:

array([ 8, 7, 3, 11, 6, 0, 9, 10, 2, 5, 4, 1])

Distributions
There are the following functions of permutations:

1) beta(a, b[, size])

This function is used to draw samples from a Beta distribution.

Example:

1. def setup(self):
2. self.dist = dist.beta
3. self.cargs = []

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
4. self.ckwd = dict(alpha=2, beta=3)
5. self.np_rand_fxn = numpy.random.beta
6. self.np_args = [2, 3]
7. self.np_kwds = dict()

2) binomial(n, p[, size])

This function is used to draw sample from a binomial distribution.

Example:

1. import numpy as np
2. n, p = 10, .6
3. s1= np.random.binomial(n, p, 10)
4. s1

Output:

array([6, 7, 7, 9, 3, 7, 8, 6, 6, 4])

3) chisquare(df[, size])

This function is used to draw sample from a binomial distribution.

Example:

1. import numpy as np
2. np.random.chisquare(2,4)
3. sum(np.random.binomial(9, 0.1, 20000) == 0)/20000.

Output:

array([6, 7, 7, 9, 3, 7, 8, 6, 6, 4])

4) dirichlet(alpha[, size])

This function is used to draw a sample from the Dirichlet distribution.

Example:

1. Import numpy as np
2. import matplotlib.pyplot as plt
3. s1 = np.random.dirichlet((10, 5, 3), 20).transpose()
4. plt.barh(range(20), s1[0])
5. plt.barh(range(20), s1[1], left=s1[0], color='g')

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
6. plt.barh(range(20), s1[2], left=s1[0]+s1[1], color='r')
7. plt.title("Lengths of Strings")
8. plt.show()

Output:

5) exponential([scale, size])

This function is used to draw sample from an exponential distribution.

Example:

1. def __init__(self, sourceid, targetid):


2. self.__type = 'Transaction'
3. self.id = uuid4()
4. self.source = sourceid
5. self.target = targetid
6. self.date = self._datetime.date(start=2015, end=2019)

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
7. self.time = self._datetime.time()
8.
9. if random() < 0.05:
10. self.amount = self._numbers.between(100000, 1000000)
11. self.amount = npr.exponential(10)
12.
13. if random() < 0.15:
14. self.currency = self._business.currency_iso_code()
15. else:
16. self.currency = None

6) f(dfnum, dfden[, size])

This function is used to draw sample from an F distribution.

Example:

1. import numpy as np
2. dfno= 1.
3. dfden = 48.
4. s1 = np.random.f(dfno, dfden, 10)
5. np.sort(s1)

Output:

array([0.00264041, 0.04725478, 0.07140803, 0.19526217, 0.23979 ,


0.24023478, 0.63141254, 0.95316446, 1.40281789, 1.68327507])

7) gamma(shape[, scale, size])

This function is used to draw sample from a Gamma distribution

Example:

1. import numpy as np
2. shape, scale = 2., 2.
3. s1 = np.random.gamma(shape, scale, 1000)
4. import matplotlib.pyplot as plt
5. import scipy.special as spss
6. count, bins, ignored = plt.hist(s1, 50, density=True)
7. a = bins**(shape-1)*(np.exp(-bins/scale) /
8. (spss.gamma(shape)*scale**shape))

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
9. plt.plot(bins, a, linewidth=2, color='r')
10. plt.show()

8) geometric(p[, size])

This function is used to draw sample from a geometric distribution.

Example:

1. import numpy as np
2. a = np.random.geometric(p=0.35, size=10000)
3. (a == 1).sum() / 1000

Output:

3.

9) gumbel([loc, scale, size])

This function is used to draw sample from a Gumble distribution.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Example:

1. import numpy as np
2. lov, scale = 0, 0.2
3. s1 = np.random.gumbel(loc, scale, 1000)
4. import matplotlib.pyplot as plt
5. count, bins, ignored = plt.hist(s1, 30, density=True)
6. plt.plot(bins, (1/beta)*np.exp(-(bins - loc)/beta)* np.exp( -np.exp( -
(bins - loc) /beta) ),linewidth=2, color='r')
7. plt.show()

Output:

10) hypergeometric(ngood, nbad, nsample[, size])

This function is used to draw sample from a Hypergeometric distribution.

Example:

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
1. import numpy as np
2. good, bad, samp = 100, 2, 10
3. s1 = np.random.hypergeometric(good, bad, samp, 1000)
4. plt.hist(s1)
5. plt.show()

Output:

(array([ 13., 0., 0., 0., 0., 163., 0., 0., 0., 824.]),
array([ 8. , 8.2, 8.4, 8.6, 8.8, 9. , 9.2, 9.4, 9.6, 9.8, 10. ]),
<a list of 10 Patch objects>)

11) laplace([loc, scale, size])

This function is used to draw sample from the Laplace or double exponential
distribution with specified location and scale.

Example:

1. import numpy as np

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
2. location, scale = 0., 2.
3. s = np.random.laplace(location, scale, 10)
4. s

Output:

array([-2.77127948, -1.46401453, -0.03723516, -1.61223942, 2.29590691,


1.74297722, 1.49438411, 0.30325513, -0.15948891, -4.99669747])

12) logistic([loc, scale, size])

This function is used to draw sample from logistic distribution.

Example:

1. import numpy as np
2. import matplotlib.pyplot as plt
3. location, scale = 10, 1
4. s1 = np.random.logistic(location, scale, 10000)
5. count, bins, ignored = plt.hist(s1, bins=50)
6. count
7. bins
8. ignored
9. plt.show()

Output:

array([1.000e+00, 1.000e+00, 1.000e+00, 0.000e+00, 1.000e+00, 1.000e+00,


1.000e+00, 5.000e+00, 7.000e+00, 1.100e+01, 1.800e+01, 3.500e+01,
5.300e+01, 6.700e+01, 1.150e+02, 1.780e+02, 2.300e+02, 3.680e+02,
4.910e+02, 6.400e+02, 8.250e+02, 9.100e+02, 9.750e+02, 1.039e+03,
9.280e+02, 8.040e+02, 6.530e+02, 5.240e+02, 3.380e+02, 2.470e+02,
1.650e+02, 1.150e+02, 8.500e+01, 6.400e+01, 3.300e+01, 1.600e+01,
2.400e+01, 1.400e+01, 4.000e+00, 5.000e+00, 2.000e+00, 2.000e+00,
1.000e+00, 1.000e+00, 0.000e+00, 1.000e+00, 0.000e+00, 0.000e+00,
0.000e+00, 1.000e+00])
array([ 0.50643911, 0.91891814, 1.33139717, 1.7438762 , 2.15635523,
2.56883427, 2.9813133 , 3.39379233, 3.80627136, 4.2187504 ,
4.63122943, 5.04370846, 5.45618749, 5.86866652, 6.28114556,
6.69362459, 7.10610362, 7.51858265, 7.93106169, 8.34354072,
8.75601975, 9.16849878, 9.58097781, 9.99345685, 10.40593588,
10.81841491, 11.23089394, 11.64337298, 12.05585201, 12.46833104,
12.88081007, 13.2932891 , 13.70576814, 14.11824717, 14.5307262 ,
14.94320523, 15.35568427, 15.7681633 , 16.18064233, 16.59312136,
17.00560039, 17.41807943, 17.83055846, 18.24303749, 18.65551652,
19.06799556, 19.48047459, 19.89295362, 20.30543265, 20.71791168,
21.13039072])
<a list of 50 Patch objects>

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
13) lognormal([mean, sigma, size])

This function is used to draw sample from a log-normal distribution.

Example:

1. import numpy as np
2. mu, sigma = 2., 1.
3. s1 = np.random.lognormal(mu, sigma, 1000)
4. import matplotlib.pyplot as plt
5. count, bins, ignored = plt.hist(s1, 100, density=True, align='mid')
6. a = np.linspace(min(bins), max(bins), 10000)
7. pdf = (np.exp(-
(np.log(a) - mu)**2 / (2 * sigma**2))/ (a * sigma * np.sqrt(2 * np.pi)))
8. plt.plot(a, pdf, linewidth=2, color='r')
9. plt.axis('tight')
10. plt.show()

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Output:

14) logseries(p[, size])

This function is used to draw sample from a logarithmic distribution.

Example:

1. import numpy as np
2. x = .6
3. s1 = np.random.logseries(x, 10000)
4. count, bins, ignored = plt.hist(s1)
5. def logseries(k, p):
6. return -p**k/(k*log(1-p))
7. plt.plot(bins, logseries(bins, x)*count.max()/logseries(bins, a).max(), 'r')
8. plt.show()

Output:

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
15) multinomial(n, pvals[, size])

This function is used to draw sample from a multinomial distribution.

Example:

1. import numpy as np
2. np.random.multinomial(20, [1/6.]*6, size=1)

Output:

array([[4, 2, 5, 5, 3, 1]])

16) multivariate_normal(mean, cov[, size, ...)

This function is used to draw sample from a multivariate normal distribution.

Example:

1. import numpy as np

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
2. mean = (1, 2)
3. coveriance = [[1, 0], [0, 100]]
4. import matplotlib.pyplot as plt
5. a, b = np.random.multivariate_normal(mean, coveriance, 5000).T
6. plt.plot(a, b, 'x')
7. plt.axis('equal'023
8. 030
9. )
10. plt.show()

Output:

17) negative_binomial(n, p[, size])

This function is used to draw sample from a negative binomial distribution.

Example:

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
1. import numpy as np
2. s1 = np.random.negative_binomial(1, 0.1, 100000)
3. for i in range(1, 11):
4. probability = sum(s1<i) / 100000.
5. print i, "wells drilled, probability of one success =", probability

Output:

1 wells drilled, probability of one success = 0


2 wells drilled, probability of one success = 0
3 wells drilled, probability of one success = 0
4 wells drilled, probability of one success = 0
5 wells drilled, probability of one success = 0
6 wells drilled, probability of one success = 0
7 wells drilled, probability of one success = 0
8 wells drilled, probability of one success = 0
9 wells drilled, probability of one success = 0
10 wells drilled, probability of one success = 0

18) noncentral_chisquare(df, nonc[, size])

This function is used to draw sample from a noncentral chi-square distribution.

Example:

1. import numpy as np
2. import matplotlib.pyplot as plt
3. val = plt.hist(np.random.noncentral_chisquare(3, 25, 100000), bins=200, nor
med=True)
4. plt.show()

Output:

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
19) normal([loc, scale, size])

This function is used to draw sample from a normal distribution.

Example:

1. import numpy as np
2. import matplotlib.pyplot as plt
3. mu, sigma = 0, 0.2 # mean and standard deviation
4. s1 = np.random.normal(mu, sigma, 1000)
5. abs(mu - np.mean(s1)) < 0.01
6. abs(sigma - np.std(s1, ddof=1)) < 0.01
7. count, bins, ignored = plt.hist(s1, 30, density=True)
8. plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *np.exp( - (bins - mu)**2 / (2 *
sigma**2) ), linewidth=2, color='r')
9. plt.show()

Output:

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
20) pareto(a[, size])

This function is used to draw samples from a Lomax or Pareto II with specified
shape.

Example:

1. import numpy as np
2. import matplotlib.pyplot as plt
3. b, m1 = 3., 2. # shape and mode
4. s1 = (np.random.pareto(b, 1000) + 1) * m1
5. count, bins, _ = plt.hist(s1, 100, density=True)
6. fit = b*m**b / bins**(b+1)
7. plt.plot(bins, max(count)*fit/max(fit), linewidth=2, color='r')
8. plt.show()

Output:

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
21) power(a[, size])

This function is used to draw samples in [0, 1] from a power distribution with
positive exponent a-1.

Example:

1. import numpy as np
2. x = 5. # shape
3. samples = 1000
4. s1 = np.random.power(x, samples)
5. import matplotlib.pyplot as plt
6. count, bins, ignored = plt.hist(s1, bins=30)
7. a = np.linspace(0, 1, 100)
8. b = x*a**(x-1.)
9. density_b = samples*np.diff(bins)[0]*b
10. plt.plot(a, density_b)

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
11. plt.show()

Output:

22) rayleigh([scale, size])

This function is used to draw sample from a Rayleigh distribution.

Example:

1. val = hist(np.random.rayleigh(3, 100000), bins=200, density=True)


2. meanval = 1
3. modeval = np.sqrt(2 / np.pi) * meanval
4. s1 = np.random.rayleigh(modeval, 1000000)
5. 100.*sum(s1>3)/1000000.

Output:

0.087300000000000003

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
23) standard_cauchy([size])

This function is used to draw sample from a standard Cauchy distribution with
mode=0.

Example:

1. import numpy as np
2. import matplotlib.pyplot as plt
3. s1 = np.random.standard_cauchy(1000000)
4. s1 = s1[(s1>-25) & (s1<25)] # truncate distribution so it plots well
5. plt.hist(s1, bins=100)
6. plt.show()

Output:

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
24) standard_exponential([size])

This function is used to draw sample from a standard exponential distribution.

Example:

1. import numpy as np
2. n = np.random.standard_exponential((2, 7000))

Output:

array([[0.53857931, 0.181262 , 0.20478701, ..., 3.66232881, 1.83882709,


1.77963295],
[0.65163973, 1.40001955, 0.7525986 , ..., 0.76516523, 0.8400617 ,
0.88551011]])

25) standard_gamma([size])

This function is used to draw sample from a standard Gamma distribution.

Example:

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
1. import numpy as np
2. shape, scale = 2., 1.
3. s1 = np.random.standard_gamma(shape, 1000000)
4. import matplotlib.pyplot as plt
5. import scipy.special as sps
6. count1, bins1, ignored1 = plt.hist(s, 50, density=True)
7. y = bins1**(shape-1) * ((np.exp(-
bins1/scale))/ (sps.gamma(shape) * scale**shape))
8. plt.plot(bins1, y, linewidth=2, color='r')
9. plt.show()

Output:

26) standard_normal([size])

This function is used to draw sample from a standard Normal distribution.

Example:

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
1. import numpy as np
2. import matplotlib.pyplot as plt
3. s1= np.random.standard_normal(8000)
4. s1
5. q = np.random.standard_normal(size=(3, 4, 2))
6. q

Output:

array([-3.14907597, 0.95366265, -1.20100026, ..., 3.47180222,


0.9608679 , 0.0774319 ])
array([[[ 1.55635461, -1.29541713],
[-1.50534663, -0.02829194],
[ 1.03949348, -0.26128132],
[ 1.51921798, 0.82136178]],

[[-0.4011052 , -0.52458858],
[-1.31803814, 0.37415379],
[-0.67077365, 0.97447018],
[-0.20212115, 0.67840888]],

[[ 1.86183474, 0.19946562],
[-0.07376021, 0.84599701],
[-0.84341386, 0.32081667],
[-3.32016062, -1.19029818]]])

27) standard_t(df[, size])

This function is used to draw sample from a standard Student's distribution with df
degree of freedom.

Example:

1. intake = np.array([5260., 5470, 5640, 6180, 6390, 6515, 6805, 7515,8230,8


770])
2. s1 = np.random.standard_t(10, size=100000)
3. np.mean(intake)
4. intake.std(ddof=1)
5. t = (np.mean(intake)-7725)/(intake.std(ddof=1)/np.sqrt(len(intake)))
6. h = plt.hist(s1, bins=100, density=True)
7. np.sum(s1<t) / float(len(s1))
8. plt.show()

Output:

6677.5
1174.1101831694598
0.00864

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
28) triangular(left, mode, right[, size])

This function is used to draw sample from a triangular distribution over the interval.

Example:

1. import numpy as np
2. import matplotlib.pyplot as plt
3. h = plt.hist(np.random.triangular(-
4, 0, 8, 1000000), bins=300,density=True)
4. plt.show()

Output:

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
29) uniform([low, high, size])

This function is used to draw sample from a uniform distribution.

Example:

1. import numpy as np
2. import matplotlib.pyplot as plt
3. s1 = np.random.uniform(-1,0,1000)
4. np.all(s1 >= -1)
5. np.all(s1 < 0)
6. count, bins, ignored = plt.hist(s1, 15, density=True)
7. plt.plot(bins, np.ones_like(bins), linewidth=2, color='r')
8. plt.show()

Output:

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
30) vonmises(m1, m2[, size])

This function is used to draw sample from a von Mises distribution.

Example:

1. import numpy as np
2. import matplotlib.pyplot as plt
3. m1, m2 = 0.0, 4.0
4. s1 = np.random.vonmises(m1, m2, 1000)
5. from scipy.special import i0
6. plt.hist(s1, 50, density=True)
7. x = np.linspace(-np.pi, np.pi, num=51)
8. y = np.exp(m2*np.cos(x-m1))/(2*np.pi*i0(m2))
9. plt.plot(x, y, linewidth=2, color='r')
10. plt.show()

Output:

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
31) wald(mean, scale[, size])

This function is used to draw sample from a Wald, or inverse Gaussian distribution.

Example:

1. import numpy as np
2. import matplotlib.pyplot as plt
3. h = plt.hist(np.random.wald(3, 3, 100000), bins=250, density=True)
4. plt.show()

Output:

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
32) weibull(a[, size])

This function is used to draw sample from a Weibull distribution.

Example:

1. import numpy as np
2. import matplotlib.pyplot as plt
3. from scipy import special
4. x=2.0
5. s=np.random.weibull(x, 1000)
6. a = np.arange(1, 100.)/50.
7. def weib(x, n, a):
8. return (a/n)*(x/n)**np.exp(-(x/n)**a)
9. count, bins, ignored = plt.hist(np.random.weibull(5.,1000))
10. a= np.arange(1,100.)/50.
11. scale = count.max()/weib(x, 1., 5.).max()

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
12. scale = count.max()/weib(a, 1., 5.).max()
13. plt.plot(x, weib(x, 1., 5.)*scale)
14. plt.show()

Output:

33) zipf(a[, size])

This function is used to draw sample from a Zipf distribution.

Example:

1. import numpy as np
2. import matplotlib.pyplot as plt
3. from scipy import special
4. x=2.0
5. s=np.random.zipf(x, 1000)
6. count, bins, ignored = plt.hist(s[s<50], 50, density=True)

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
7. a = np.arange(1., 50.)
8. b= a**(-x) / special.zetac(x)
9. plt.plot(a, b/max(b), linewidth=2, color='r')
10. plt.show()

Output:

numpy.zeros() in Python
The numpy.zeros() function is one of the most significant functions which is used in
machine learning programs widely. This function is used to generate an array
containing zeros.

The numpy.zeros() function provide a new array of given shape and type, which is
filled with zeros.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Syntax
1. numpy.zeros(shape, dtype=float, order='C'
Parameters
shape: int or tuple of ints

This parameter is used to define the dimensions of the array. This parameter is used
for the shape in which we want to create an array, such as (3,2) or 2.

dtype: data-type(optional)

This parameter is used to define the desired data-type for the array. By default, the
data-type is numpy.float64. This parameter is not essential for defining.

order: {'C','F'}(optional)

This parameter is used to define the order in which we want to store data in memory
either row-major(C-style) or column-major(Fortran-style)

Return
This function returns a ndarray. The output array is the array with specified shape,
dtype, order, and contains zeros.

Example 1: numpy.zeros() without dtype and order


1. import numpy as np
2. a=np.zeros(6)
3. a

Output:

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
array([0., 0., 0., 0., 0., 0.])

In the above code

o We have imported numpy with alias name np.

o We have declared the variable 'a' and assigned the returned value of
np.zeros() function.

o We have passed an integer value in the function.

o Lastly, we tried to print the value of 'a'.

In the output, an array with floating-point integers(zeros) has been shown.

Example 2: numpy.zeros() without order


1. import numpy as np
2. a=np.zeros((6,), dtype=int)
3. a

Output:

array([0, 0, 0, 0, 0, 0])

Example 3: numpy.zeros() with shape


1. import numpy as np
2. a=np.zeros((6,2))
3. a

Output:

array([[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.]])

In the above code

o We have imported numpy with alias name np.

o We have declared the variable 'a' and assigned the returned value of
np.zeros() function.

o We have passed the shape for the array elements.

o Lastly, we tried to print the value of 'a'.

In the output, an array of given shape has been shown.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Example 4: numpy.zeros() with the shape
1. Import numpy as np
2. s1=(3,2)
3. a=np.zeros(s1)
4. a

Output:

array([[0., 0.],
[0., 0.],
[0., 0.]])

Example 5: numpy.zeros() with custom dtype


1. Import numpy as np
2. a=np.zeros((3,), dtype=[('x', 'i4'), ('y', 'i4')])
3. a

Output:

array([(0, 0), (0, 0), (0, 0)], dtype=[('x', '<i4'), ('y', '<i4')])

In the above code

o We have imported numpy with alias name np.

o We have declared the variable 'a' and assigned the returned value of
np.zeros() function.

o We have passed the shape and custom data type in the function.

o Lastly, we tried to print the value of 'a'.

In the output, an array contains zeros with custom data-type has been shown

numpy.log() in Python
The numpy.log() is a mathematical function that is used to calculate the natural
logarithm of x(x belongs to all the input array elements). It is the inverse of the
exponential function as well as an element-wise natural logarithm. The natural
logarithm log is the reverse of the exponential function, so that log(exp(x))=x. The
logarithm in base e is the natural logarithm.

Syntax
1. numpy.log(x, /, out=None, *, where=True, casting='same_kind', order='K', d
type=None, subok=True[, signature, extobj]) = <ufunc 'log'>

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Parameters
x: array_like

This parameter defines the input value for the numpy.log() function.

out: ndarray, None, or tuple of ndarray and None(optional)

This parameter is used to define the location in which the result is stored. If we
define this parameter, it must have a shape similar to the input broadcast;
otherwise, a freshly-allocated array is returned. A tuple has a length equal to the
number of outputs.

where: array_like(optional)

It is a condition that is broadcast over the input. At this location, where the
condition is True, the out array will be set to the ufunc(universal function) result;
otherwise, it will retain its original value.

casting: {'no','equiv','safe','same_kind','unsafe'}(optional)

This parameter controls the kind of data casting that may occur. The 'no' means the
data types should not be cast at all. The 'equiv' means only byte-order changes are
allowed. The 'safe' means the only cast, which can allow the preserved value. The
'same_kind' means only safe casts or casts within a kind. The 'unsafe' means any
data conversions may be done.

order: {'K', 'C', 'F', 'A'}(optional)

This parameter specifies the calculation iteration order/ memory layout of the output
array. By default, the order will be K. The order 'C' means the output should be C-
contiguous. The order 'F' means F-contiguous, and 'A' means F-contiguous if the
inputs are F-contiguous and if inputs are in C-contiguous, then 'A' means C-
contiguous. 'K' means to match the element ordering of the inputs(as closely as
possible).

dtype: data-type(optional)

It overrides the dtype of the calculation and output arrays.

subok: bool(optional)

By default, this parameter is set to true. If we set it to false, the output will always
be a strict array, not a subtype.

signature

This argument allows us to provide a specific signature to the 1-d loop 'for', used in
the underlying calculation.

extobj

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
This parameter is a list of length 1, 2, or 3 specifying the ufunc buffer-size, the error
mode integer, and the error callback function.

Returns
This function returns a ndarray that contains the natural logarithmic value of x,
which belongs to all elements of the input array.

Example 1:
1. import numpy as np
2. a=np.array([2, 4, 6, 3**8])
3. a
4. b=np.log(a)
5. b
6. c=np.log2(a)
7. c
8. d=np.log10(a)
9. d

Output:

array([ 2, 4, 6, 6561])
array([0.69314718, 1.38629436, 1.79175947, 8.78889831])
array([ 1. , 2. , 2.5849625 , 12.67970001])
array([0.30103 , 0.60205999, 0.77815125, 3.81697004])

In the above mentioned code

o We have imported numpy with alias name np.

o We have created an array 'a' using np.array() function.

o We have declared variable b, c, and, d and assigned the returned value of


np.log(), np.log2(), and np.log10() functions respectively.

o We have passed the array 'a' in all the functions.

o Lastly, we tried to print the value of b, c, and d.

In the output, a ndarray has been shown, contains the log, log2, and log10 values of
all the elements of the source array.

Example 2:
1. import numpy as np
2. import matplotlib.pyplot as plt
3. arr = [2, 2.2, 2.4, 2.6,2.8, 3]
4. result1=np.log(arr)

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
5. result2=np.log2(arr)
6. result3=np.log10(arr)
7. plt.plot(arr,arr, color='blue', marker="*")
8. plt.plot(result1,arr, color='green', marker="o")
9. plt.plot(result2,arr, color='red', marker="*")
10. plt.plot(result3,arr, color='black', marker="*")
11. plt.show()

Output:

In the above code

o We have imported numpy with alias name np.

o We have also imported matplotlib.pyplot with alias name plt.

o Next, we have created an array 'arr' using np.array() function.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
o After that we declared variable result1, result2, result3 and assigned the
returned values of np.log(), np.log2(), and np.log10() functions respectively.

o We have passed the array 'arr' in all the functions.

o Lastly, we tried to plot the values of 'arr', result1, result2, and result3.

In the output, a graph with four straight lines with different colors has been shown.

Example 3:
1. import numpy as np
2. x=np.log([2, np.e, np.e**3, 0])
3. x

Output:

__main__:1: RuntimeWarning: divide by zero encountered in log


array([0.69314718, 1. , 3. , -inf])

In the above code

o Firstly, we have imported numpy with alias name np.

o We have declared the variable 'x' and assigned the returned value of np.log()
functions.

o We have passed different values in the function, such as integer value, np.e,
and np.e**2.

o Lastly, we tried to print the value of 'x'.

In the output, a ndarray has been shown, contains the log values of the elements of
the source array.

numpy.where() in Python
The NumPy module provides a function numpy.where() for selecting elements based
on a condition. It returns elements chosen from a or b depending on the condition.

For example, if all arguments -> condition, a & b are passed in numpy.where() then
it will return elements selected from a & b depending on values in bool array yielded
by the condition.

If only the condition is provided, this function is a shorthand to the function


np.asarray (condition).nonzero(). Although nonzero should be preferred directly, as
it behaves correctly for subclasses.

Syntax:
1. numpy.where(condition[, x, y])

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Parameters:
These are the following parameters in numpy.where() function:

condition: array_like, bool

If this parameter set to True, yield x otherwise yield y.

x, y: array_like:

This parameter defines the values from which to choose. The x, y, and condition
need to be broadcastable to some shape.

Returns:
This function returns the array with elements from x where the condition is True and
elements from y elsewhere.

Example 1: np.where()
1. import numpy as np
2. a=np.arange(12)
3. b=np.where(a<6,a,5*a)
4. b

In the above code

o We have imported numpy with alias name np.

o We have created an array 'a' using np.arange() function.

o We have declared the variable 'b' and assigned the returned value of
np.where() function.

o We have passed the array 'a' in the function.

o Lastly, we tried to print the value of b.

In the output, the values ranging from 0 to 5 remain the same as per the condition,
and the other values have been multiplied with 5.

Output:

array([ 0, 1, 2, 3, 4, 5, 30, 35, 40, 45, 50, 55])

Example 2: For multidimensional array


1. import numpy as np
2. a=np.arange(12)
3. b=np.where([[True, False], [True, True]],[[1, 2], [3, 4]],[[9, 8], [7, 6]])

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
4. b

Output:

array([[1, 8],
[3, 4]])

Example 3: Broadcasting x, y, and condition


1. import numpy as np
2. x, y = np.ogrid[:3, :4]
3. a=np.where(x > y, x, 10 + y)
4. a

Output:

array([[10, 11, 12, 13],


[ 1, 11, 12, 13],
[ 2, 2, 12, 13]])

In the above code

o We have imported numpy with alias name np.

o We have created an array 'a' using np.arange() function.

o We declared the variable 'b' and assigned the returned value of np.where()
function.

o We have passed a multidimensional array of boolean as a condition and x and


y as an integer arrays.

o Lastly, we tried to print the value of b.

In the output, the x value has been compared to y value if it satisfied the condition,
then it will be printed x value otherwise, it will print y value, which has passed as an
argument in the where() function.

Example 4: Broadcasting specific value


1. x=np.array([[0,1,2],[0,2,5],[0,4,8]])
2. y=np.where(x<4,x,-2)
3. y

Output:

array([[ 0, 1, 2],
[ 0, 2, -2],
[ 0, -2, -2]])

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
numpy.argsort() in Python
The NumPy module provides a function argsort(), returns the indices which would
sort an array.

The NumPy module provides a function for performing an indirect sort along with the
given axis with the help of the algorithm specified by the keyword. This function
returns an array of indices of the same shape as 'a', which would sort the array.

Syntax
1. numpy.argsort(a, axis=-1, kind=None, order=None)
Parameters
These are the following parameters in numpy.argsort() function:

a: array_like

This parameter defines the source array which we want to sort.

axis: int or None(optional)

This parameter defines the axis along which the sorting is performed. By default, the
axis is -1. If we set this parameter to None, the flattened array is used.

kind: {'quicksort','mergesort','heapsort','stable'}(optional)

This parameter defines the sorting algorithm. By default, the algorithm is quicksort.
Both mergesort and stable are using time sort under the covers. The actual
implementation will vary with the data type. The mergesort option is retained for
backward compatibility.

order: str or list of str(optional)

If 'a' is an array with defined fields, this argument specifies which fields to compare
first, second, etc. The single field can be specified as a string, and not all fields need
to be specified. But unspecified fields will still use, in the order in which they come
up in the dtype, to break the ties.

Returns: index_array: ndarray, int


This function returns an array of indices which sort 'a' along with the specified axis.
If 'a' is 1-D, a[index_array] yields a sorted 'a'. More
generally, np.take_along_axis(arr1, index_array, axis=axis) always yields the
sorted 'a', irrespective of dimensionality.

Example 1: np.argsort()
1. import numpy as np
2. a=np.array([456,11,63])

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
3. a
4. b=np.argsort(a)
5. b

In the above code

o We have imported numpy with alias name np.

o We have created an array 'a' using np.array() function.

o We have declared the variable 'b' and assigned the returned value of
np.argsort() function.

o We have passed the array 'a' in the function.

o Lastly, we tried to print the value of b.

In the output, a ndarray has been shown that contains the indices(indicate the
position of the element for the sorted array) and dtype.

Output:

array([456, 11, 63])


array([1, 2, 0], dtype=int64)

Example 2: For 2-D array( sorts along first axis (down))


1. import numpy as np
2. a = np.array([[0, 5], [3, 2]])
3. indices = np.argsort(a, axis=0)
4. indices

Output:

array([[0, 1],
[1, 0]], dtype=int64)

Example 3: For 2-D array(alternative of axis=0)


1. import numpy as np
2. a = np.array([[0, 5], [3, 2]])
3. indices = np.argsort(a, axis=0)
4. indices
5. np.take_along_axis(a, indices, axis=0)

In the above code

o We have imported numpy with alias name np.

o We have created a 2-D array 'a' using np.array() function.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
o We have declared variable indices and assigned the returned value of
np.argsort() function.

o We have passed the 2-D array 'a' and axis as 0.

o Next, we used the take_along_axis() function and passed the source array,
indices, and axis.

o This function has returned the sorted 2-D array.

In the output, a 2-D array with sorted elements has been shown.

Output:

array([[0, 2],
[3, 5]])

Example 4: For 2-D array( sorts along last axis (across))


1. import numpy as np
2. a = np.array([[0, 5], [3, 2]])
3. indices = np.argsort(a, axis=1)
4. indices

Output:

array([[0, 1],
[1, 0]], dtype=int64)

Example 5: For 2-D array(alternative of axis=1)


1. import numpy as np
2. a = np.array([[0, 5], [3, 2]])
3. indices = np.argsort(a, axis=1)
4. indices
5. np.take_along_axis(a, indices, axis=1)

Output:

array([[0, 2],
[3, 5]])

Example 6: For N-D array


1. import numpy as np
2. a = np.array([[0, 5], [3, 2]])
3. indices = np.unravel_index(np.argsort(a, axis=None), a.shape)
4. indices
5. a[indices] # same as np.sort(a, axis=None)

Output:

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
(array([0, 1, 1, 0], dtype=int64), array([0, 1, 0, 1], dtype=int64))
array([0, 2, 3, 5])

In the above code

o We have imported numpy with alias name np.

o We have created a 2-D array 'a' using np.array() function.

o We have declared a variable 'indices' and assigned the returned value of


np.unravel_index() function.

o We have passed the np.argsort() function and shape of the array 'a'.

o We have passed the 2-D array 'a' and axis as 1 in argsort() function.

o Next, we tried to print the value of indices and a[indices].

In the output, an N-D array with sorted elements has been shown.

Example 7: Sorting with keys


1. import numpy as np
2. a= np.array([(0, 5), (3, 2)], dtype=[('x', '<i4'), ('y', '<i4')])
3. a
4. b=np.argsort(a, order=('x','y'))
5. b
6. c=np.argsort(a, order=('y','x'))
7. c

Output:

array([(0, 5), (3, 2)], dtype=[('x', '<i4'), ('y', '<i4')])


array([0, 1], dtype=int64)
array([1, 0], dtype=int64)

In the above code

o We have imported numpy with alias name np.

o We have created a 2-D array 'a' using np.array() function with dtype=[('x',
'<i4'), ('y', '<i4')].

o We have declared the variables 'b' and 'c' and assigned the returned value of
np.argsort() function.

o We have passed the array 'a' and order as an argument in the function.

o Lastly, we tried to print the value of 'b' and 'c'.

In the output, a sorted array has been shown with dtype=[('x', '<i4'), ('y', '<i4')]

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
numpy.transpose() in Python
The numpy.transpose() function is one of the most important functions in matrix
multiplication. This function permutes or reserves the dimension of the given array
and returns the modified array.

The numpy.transpose() function changes the row elements into column elements
and the column elements into row elements. The output of this function is a
modified array of the original one.

Syntax
1. numpy.transpose(arr, axis=None)
Parameters
arr: array_like

It is an ndarray. It is the source array whose elements we want to transpose. This


parameter is essential and plays a vital role in numpy.transpose() function.

axis: List of ints()

If we didn't specify the axis, then by default, it reverses the dimensions otherwise
permute the axis according to the given values.

Return
This function returns a ndarray. The output array is the source array, with its axis
permuted. A view is returned whenever possible.

Example 1: numpy.transpose()
1. import numpy as np
2. a= np.arange(6).reshape((2,3))
3. a
4. b=np.transpose(a)
5. b

Output:

array([[0, 1, 2],
[3, 4, 5]])
array([[0, 3],
[1, 4],
[2, 5]])

In the above code

o We have imported numpy with alias name np.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
o We have created an array 'a' using np.arange() function and gave a shape
using reshape() function.

o We have declared the variable 'b' and assigned the returned value of
np.transpose() function.

o We have passed the array 'a' in the function.

o Lastly, we tried to print the value of b.

In the output, the transposed array of the original array has been shown.

Example 2: numpy.transpose() with axis


1. import numpy as np
2. a= np.array([[1, 2], [4, 5], [7, 8]])
3. a
4. b=np.transpose(a, (1,0))
5. b

Output:

array([[1, 2],
[4, 5],
[7, 8]])
array([[1, 4, 7],
[2, 5, 8]])

In the above code

o We have imported numpy with alias name np.

o We have created an array 'a' using np.array() function.

o We have declared the variable 'b' and assigned the returned value of
np.transpose() function.

o We have passed the array 'a' and the axis in the function.

o Lastly, we tried to print the value of b.

In the output, the transposed array of the original array has been shown.

Example 3: Reposition elements using numpy.transpose()


1. import numpy as np
2. a=np.ones((12,32,123,64))
3. b=np.transpose(a,(1,3,0,2)).shape
4. b
5. c=np.transpose(a,(0,3,1,2)).shape

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
6. c

Output:

(32L, 64L, 12L, 123L)


(12L, 64L, 32L, 123L)

o We have imported numpy with alias name np.

o We have created an array 'a' using np.ones() function.

o We have declared the variable 'b' and 'c' and assigned the returned value of
np.transpose() function.

o We have passed the array 'a' and the positions of the array elements in the
function.

o Lastly, we tried to print the value of b and c.

In the output, an array has been shown whose elements are located at the defined
position in the array.

numpy.mean() in Python
The sum of elements, along with an axis divided by the number of elements, is
known as arithmetic mean. The numpy.mean() function is used to compute the
arithmetic mean along the specified axis.

This function returns the average of the array elements. By default, the average is
taken on the flattened array. Else on the specified axis, float 64 is intermediate as
well as return values are used for integer inputs

Syntax
1. numpy.mean(a, axis=None, dtype=None, out=None, keepdims=<no value>)

Parameters
These are the following parameters in numpy.mean() function:

a: array_like

This parameter defines the source array containing elements whose mean is desired.
In such a case where 'a' is not an array, a conversion is attempted.

axis: None, int or tuple of ints(optional)

This parameter defines the axis along which the means are computed. By default,
the mean is computed of the flattened array. In version 1.7.0, if this is a tuple of

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
ints, the mean is performed over multiple axes, instead of a single axis or all the
axes as before.

dtype: data-type(optional)

This parameter is used to define the data-type used in computing the mean. For
integer inputs, the default is float64, and for floating-point inputs, it is the same as
the input dtype.

out: ndarray(optional)

This parameter defines an alternative output array in which the result will be placed.
The shape of the resulting array should be the same as the shape of the expected
output. The type of output values will cast when necessary.

keepdims: bool(optional)

When the value is true, the reduced axis is left as dimensions with size one in the
output/result. Also, the result broadcasts correctly against the input array. When the
default value is set, the keepdims does not pass via the mean method of sub-classes
of ndarray, but any non-default value will surely pass. In case the sub-class method
does not implement keepdims, then an exception will surely rise.

Return
If we set the 'out' parameter to None, this function returns a new array containing
the mean values. Otherwise, it will return the reference to the output array.

Example 1:
1. import numpy as np
2. a = np.array([[1, 2], [3, 4]])
3. b=np.mean(a)
4. b
5. x = np.array([[5, 6], [7, 34]])
6. y=np.mean(x)
7. y

Output:

2.5
13.0

In the above code

o We have imported numpy with alias name np.

o We have created two arrays 'a' and 'x' using np.array() function.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
o We have declared the variable 'b' and 'y' and assigned the return value of
np.zeros() function.

o We have passed arrays 'a' and 'x' in the function.

o Lastly, we tried to print the value of 'b' and 'y'.

Example 2:
1. import numpy as np
2. a = np.array([[2, 4], [3, 5]])
3. b=np.mean(a,axis=0)
4. c=np.mean(a,axis=1)
5. b
6. c

Output:

array([2.5, 4.5])
array([3., 4.])

Example 3:
In single precision, mean can be inaccurate:

1. import numpy as np
2. a = np.zeros((2, 512*512), dtype=np.float32)
3. a[0, :] = 23.0
4. a[1, :] = 32.0
5. c=np.mean(a)
6. c

Output:

27.5

In the above code

o We have imported numpy with alias name np.

o We have created an array 'a' using np.zeros() function with dtype float32.

o We have set the value of all the elements of 1st row to 23.0 and 2nd row
32.0.

o We have passed the array 'a' in the function and assigned the return value of
the np.mean() function.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
o Lastly, we tried to print the value of 'c'.

In the output, it shows the mean of array 'a'.

Example 4:
Computing the mean in float64 is more accurate:

1. import numpy as np
2. a[0, :] = 2.0
3. a[1, :] = 0.2
4. c=np.mean(a)
5. c
6. d=np.mean(a, dtype=np.float64)
7. d

Output:

1.0999985
1.1000000014901161

numpy.unique() in Python
The numpy module of Python provides a function for finding unique elements in a
numpy array. The numpy.unique() function finds the unique elements of an array
and returns these unique elements as a sorted array. Apart from the unique
elements, there are some optional outputs also, which are as follows:

o The output can be the indices of the input array which give the unique values

o The output can be the indices of the unique array which reconstruct the input
array

o The output can be an array of the number of times each unique value comes
in the input array.

Syntax
1. numpy.unique(a, return_index=False, return_inverse=False, return_counts=F
alse, axis=None)
Parameters
These are the following parameters in numpy.mean() function:

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
a: array_like

This parameter defines the source array containing elements whose unique values
are desired. The array will be flattened if it is not 1-D array.

Return_index: bool(optional)

If this parameter is set True, the function will return the indices of the input
array(along the specified axis if provided or in the flattened array), which results in
the unique array.

return_inverse: bool(optional)

If this parameter is set True, the function will also return the indices of the input
array(along the specified axis if provided or in the flattened array), which can be
used to reconstruct the input array.

Return_counts: bool(optional)

If this parameter is set True, the function will return the number of times each
unique item appeared in the input array 'a'.

axis: int or None(optional)

This parameter defines the axis to operate on. If this parameter is not set, then the
array 'a' will be flattened. If this parameter is an integer, then the subarrays indexed
by the given axis will be flattened and treated as an element of a 1-D array with the
dimension of the given axis. Structured arrays or object arrays that contain objects
are not supported if the axis 'kwarg' is used.

Returns
This function returns four types of outputs which are as follows:

unique: ndarray

In this output, a ndarray will be shown that contain sorted unique values.

unique_indices: ndarray(optional)

In this output, a ndarray will be shown that contains the indices of the first
occurrences of the unique values in the original array. This output is only provided if
return_index is True.

unique_inverse: ndarray(optional)

In this output, a ndarray will be shown that contains the indices to reconstruct the
original array from the unique array. This output is only provided if return_inverse is
True.

unique_counts: ndarray(optional)

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
In this output, a ndarray will be shown that contains the number of times each of
the unique values comes up in the original array. This output is only provided if
return_counts is True.

Example 1:
1. import numpy as np
2. a=np.unique([1,2,3,4,3,6,2,4])
3. a

Output:

array([1, 2, 3, 4, 6])

In the above code

o We have imported numpy with alias name np.

o We have declared the variable 'a' and assigned the returned value of
np.unique() function.

o We have passed the number of elements in the function.

o Lastly, we tried to print the value of 'a'.

In the output, a ndarray has been shown, which contains unique elements.

Example 2:
1. a=np.array([[1,2,2,3,9],[1,4,3,5,8]])
2. a
3. b=np.unique(a)
4. b

Output:

array([[1, 2, 2, 3, 9],
[1, 4, 3, 5, 8]])
array([1, 2, 3, 4, 5, 8, 9])

Example 3:
1. import numpy as np
2. a = np.array([[1, 1, 0], [1, 1, 0], [2, 3, 4],[5, 9, 8],[2, 3, 4]])
3. a
4. b=np.unique(a, axis=0)
5. b

Output:

array([[1, 1, 0],

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
[1, 1, 0],
[2, 3, 4],
[5, 9, 8],
[2, 3, 4]])
array([[1, 1, 0],
[2, 3, 4],
[5, 9, 8]])

In the above code

o We have imported numpy with alias name np.

o We have created a multi-dimensional array 'a'.

o We have declared the variable 'b' and assigned the returned value of
np.unique() function.

o We have passed the multi-dimensional array 'a' and axis as 0 in the function.

o Lastly, we tried to print the value of 'b'.

In the output, a ndarray has been shown that contains unique rows of the source
array 'a'.

Example 4:
1. import numpy as np
2. a = np.array([[1, 1, 0], [1, 1, 0], [2, 2, 4],[5, 5, 8],[2, 2, 4]])
3. a
4. b=np.unique(a, axis=1)
5. b

Output:

array([[1, 1, 0],
[1, 1, 0],
[2, 2, 4],
[5, 5, 8],
[2, 2, 4]])
array([[0, 1],
[0, 1],
[4, 2],
[8, 5],
[4, 2]])
Note: When we set axis as 1 then this function returns the unique columns from
the source array.
Example 5: Use return_index
1. import numpy as np
2. a = np.array(['d', 'b', 'b', 'z', 'a'])
3. result, indices=np.unique(a,return_index=True)
4. result

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
5. indices
6. a[indices]

Output:

array(['a', 'b', 'd', 'z'], dtype='|S1')


array([4, 1, 0, 3], dtype=int64)
array(['a', 'b', 'd', 'z'], dtype='|S1')

In the above code

o We have imported numpy with alias name np.

o We have created an array 'a'.

o We have declared the variable 'result' and 'indices' and assigned the returned
value of np.unique() function.

o We have passed the array 'a' and set return_index to True in the function.

o Lastly, we tried to print the value of 'result', 'indices', and array elements,
which indicates the indices('a [indices]').

In the output, a ndarray has been shown that contains the indices of the original
array that give unique values.

Example 6: Use return_inverse


We can reconstruct the input array from the unique values in the following way:

1. import numpy as np
2. a = np.array([1, 2, 6, 4, 5, 3, 2])
3. result, indices=np.unique(a,return_inverse=True)
4. result
5. indices
6. a[indices]

Output:

array([1, 2, 3, 4, 5, 6])
array([0, 1, 5, 3, 4, 2, 1], dtype=int64)
array([1, 2, 3, 4, 5, 6, 2])

numpy.ndarray.tolist() in Python
The numpy module provides a function numpy.ndarray.tolist(), used to convert
the data elements of an array into a list. This function returns the array as
an a.ndim- levels deep nested list of Python scalars.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
In simple words, this function returns a copy of the array elements as a Python list.
The elements are converted to the nearest compatible built-in Python type through
the item function. When 'a.ndim' is 0, then the depth of the list is 0, and it will be a
simple Python scalar, not any list.

Syntax
1. ndarray.tolist()
Parameters
This function has no arguments or parameters.

Returns: y: object, or list of object, or list of object


This function returns the possibly nested list of array elements.

Note
We can re-create the array via a=np.array(a.tolist()), however it can sometimes
lose precision.
Example 1:
If we will use a.tolist() for a 1D array then it will be almost the same as list(a),
except that tolist converts numpy scalars to Python scalars.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
1. import numpy as np
2. a = np.uint32([6, 2])
3. a
4. a_list=list(a)
5. a_list
6. type(a_list[0])
7. a_tolist=a.tolist()
8. a_tolist
9. type(a_tolist[0])

Output:

array([6, 2], dtype=uint32)


[6, 2]
<type 'numpy.uint32'>
[6L, 2L]
<type 'long'>

In the above code

o We have imported numpy with alias name np.

o We have created an array 'a' using np.uint32() function.

o We have declared the variable 'a_list' and assigned the returned value of
the list() function.

o We tried to print the value of 'a', 'a_list', and type of a_list.

o We have declared the variable a_tolist and assigned the returned value
of ndarray.tolist().

o Lastly, we tried to print the type and the value of 'a_tolist'.

In the output, it shows a list and the type whose elements are transformed from the
source array.

Example 2:
For a 2-dimensional array, tolist is applied recursively.

1. import numpy as np
2. a = np.array([[11, 21], [31, 41]])
3. b=a.tolist()
4. a
5. b

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Output:

array([[11, 21],
[31, 41]])
[[11, 21], [31, 41]]

In the above code

o We have imported numpy with alias name np.

o We have created a 2-dimensional array 'a' using the np.array() function.

o We have declared the variable 'b' and assigned the returned value
of a.tolist() function.

o Lastly, we tried to print the value of 'b'.

In the output, it shows a list whose elements are transformed from the source array.

Example 3:
1. import numpy as np
2. x = np.array(5)
3. list(x)
4. y=x.tolist()
5. y

Output:

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
TypeError: iteration over a 0-d array
5

Next →← Prev

numpy.dot() in Python
The numpy module of Python provides a function to perform the dot product of
two arrays.

o If both the arrays 'a' and 'b' are 1-dimensional arrays, the dot() function
performs the inner product of vectors (without complex conjugation).

o If both the arrays 'a' and 'b' are 2-dimensional arrays, the dot() function
performs the matrix multiplication. But for matrix multiplication use
of matmul or 'a' @ 'b' is preferred.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
o If either 'a' or 'b' is 0-dimensional (scalar), the dot() function performs
multiplication. Also, the use of numpy.multiply(a, b) or a *b method is
preferred.

o If 'a' is an N-dimensional array and 'b' is a 1-dimensional array, then the


dot() function performs the sum-product over the last axis of a and b.

o If 'a' is an M-dimensional array and 'b' is an N-dimensional array (where


N>=2), then the dot() function performs the sum-product over the last
axis of 'a' and the second-to-last axis of 'b':

1. dot(a, b)[i,j,k,n] = sum(a[i,j,:] * b[k,:,n])


Syntax
1. numpy.dot(a, b, out=None)
Parameters

a: array_like

This parameter defines the first array.

b: array_like

This parameter defines the second array.

out: ndarray(optional)

It is an output argument. It should have the exact kind which would be returned
in the case when it was not used. Particularly, it should meet the performance
feature, i.e., it must contain the right type, i.e., it must be C-contiguous, and its
dtype must be the dtype that would be returned for dot(a,b). Thus, if it does not
meet these specified conditions, it raises an exception.

Returns

This function returns the dot product of 'a' and 'b'. This function returns a scalar if
'a' and 'b' are both scalars or 1-dimensional; otherwise, it returns an array. If
'out' is given, then it is returned.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Raises

The ValueError occurs when the last dimension of 'a' is not having the same size
as the second-to-last dimension of 'b'.

Example 1:
1. import numpy as np
2. a=np.dot(6,12)
3. a

Output:

72

Example 2:
1. import numpy as np
2. a=np.dot([2j, 3j], [5j, 8j])
3. a

Output:

(-34+0j)

Example 3:
1. import numpy as np
2. a = [[1, 2], [4, 1]]
3. b = [[4, 11], [2, 3]]
4. c=np.dot(a, b)
5. c

Output:

array([[ 8, 17],
[18, 47]])

In the above code

o We have imported numpy with alias name np.

o We have created two 2-dimensional arrays 'a' and 'b'.

o We have declared the variable 'c' and assigned the returned value
of np.dot() function.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Lastly, we tried to print the value of 'c'.

In the output, it shows the matrix product as an array.

Example 4:
1. import numpy as np
2. x = np.arange(3*4*5*6).reshape((3,4,5,6))
3. y = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3))
4. p=np.dot(a, b)[2,3,2,1,2,2]
5. q=sum(a[2,3,2,:] * b[1,2,:,2])
6. p
7. q

Output:

499128
499128

In the above code

o We have imported numpy with alias name np.

o We have created two arrays 'a' and 'b' using np.arange() function and
change the shape of both the arrays using reshape() function.

o We have declared the variable 'c' and assigned the returned value
of np.dot() function

o Lastly, we tried to print the 'c' value.

In the output, it shows the matrix product as an array.

numpy.loadtxt() in Python
The numpy module of Python provides a function to load data from a text file. The
numpy module provides loadtxt() function to be a fast reader for simple text files.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Note: In the text file, each row must have the same number of values.
Syntax
1. numpy.loadtxt(fname, dtype=<type 'float'>, comments='#', delimiter=None,
converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)
Parameters
These are the following parameter in numpy.loadtxt() function:

fname: file, str, or pathlib.Path

This parameter defines the file, filename, or generator to read. Firstly, we will
decompose the file, if the filename extension is .gz and .bz2. After that the
generators will return byte strings for Python 3k.

dtype: data-type(optional)

This parameter defines the data type for the resulting array, and by default, the
data type will be the float. The resulting array will be 1-dimensional when it is a
structured data-type. Each row is interpreted as an array element, and the number
of columns used must match with the number of fields in the data-type.

comments: str or sequence(optional)

This parameter defines the characters or list of characters used for indicating the
start of the comment. By default, it will be '#'.

delimiter: str(optional)

This parameter defines the string used for separating values. By default, it will be
any whitespace.

converters: dict(optional)

This parameter defines a dictionary mapping column number to a function that will
convert the mapped column to the float. When column() is a date string
then converters={0:datestr2num}. This parameter is also used to provide a
default value for missing data as converters= {3: lambda s: float(s.strip() or
0)}.

skiprows: int(optional)

This parameter is used to skip the first 'skiprows', and by default, it will be 0.

usecols: int or sequence(optional)

This parameter defines the columns to read, with 0 being the first. For example,
usecols=(0, 3, 5) will extract the 1st, 4th, and 5th column. By default, its value is
None, which results in all columns being read. In the new version, we can use an
integer instead of a tuple if we want to read a single column.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
unpack: bool(optional)

If this parameter is set to true, then the returned array is transposed, so that
arguments may be unpacked using x, y, z =loadtxt(...). The arrays are returned
for each field when using it with the structured data-type. By default, it will be set to
False.

ndim: int(optional)

The returned array will have 'ndmin' dimensions. Otherwise, it will squeeze the
mono-dimensional axis. Legal values: 0 (default), 1 or 2.

Returns: out(ndarray)
It reads data from the text file in the form of a ndarray.

Example 1:
1. import numpy as np
2. from io import StringIO
3. c = StringIO(u"0 1\n2 3")
4. c
5. np.loadtxt(c)

Output:

<_io.StringIO object at 0x000000000A4C3E48>


array([[0., 1.],
[2., 3.]])

In the above code

o We have imported numpy with alias name np.

o We have also imported StringIO from io.

o We have declared the variable 'c' and assigned the returned value of the
StringIO() function.

o We have passed the unicode data in the function.

o Lastly, we tried to print the return value of np.loadtxt() in which we passed


the file or filename.

In the output, it shows the content of the file in the form of ndarray.

Example 2:
1. import numpy as np
2. from io import StringIO

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
3. d = StringIO(u"M 21 72\nF 35 58")
4. np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'),'formats': ('S1', 'i4', '
f4')})

Output:

array([('M', 21, 72.), ('F', 35, 58.)], dtype=[('gender', 'S1'), ('age',


'<i4'), ('weight', '<f4')])

Example 3:
1. import numpy as np
2. from io import StringIO
3. c = StringIO(u"1,3,2\n3,5,4")
4. x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True)
5. x
6. y

Output:

array([1., 3.])
array([2., 4.])

In the above code

o We have imported numpy with alias name np.

o We have also imported StringIO from io.

o We have declared the variable 'c' and assigned the returned value of the
StringIO() function.

o We have passed the unicode data in the function.

o Lastly, we tried to print the return value of np.loadtxt in which we passed the
file or filename, set delimiter, usecols, and unpack to True.

In the output, it displays the content of the file has been shown in the form of
ndarray.

numpy.clip() in Python
For clipping the values in an array, the numpy module of Python provides a function
called numpy.clip(). In the clip() function, we will pass the interval, and the values
which are outside the interval will be clipped for the interval edges.

If we specify an interval of [1, 2] then the values smaller than 1 become 1 and
larger than 2 is 2. This function is similar to numpy.maximum(x_min,

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
numpy.maximum(x, x_max)). But it is faster than np.maximum().
In numpy.clip(), there is no need to perform check for ensuring x_min < x_max.

Syntax:
1. numpy.clip(a, a_min, a_max, out=None)
Parameters:
x: array_like

This parameter defines the source array whose elements we want to clip.

x_min: None, scalar, or array_like

This parameter defines the minimum value for clipping values. On the lower interval
edge, clipping is not required.

x_max: None, scalar, or array_like

This parameter defines the maximum value for clipping values. On the upper interval
edge, clipping is not required. The three arrays are broadcasted for matching their
shapes with x_min and x_max arrays. This will be done only when x_min and x_max
are array_like.

out: ndaaray(optional)

This parameter defines the ndarray in which the result will be stored. For in-place
clipping, this can be an input array. The data type of this 'out' arrays have the right
shape for holding the output.

Returns
clip_arr: ndarray

This function returns an array that contains the elements of 'x' but the values which
are less than the x_min, they get replaced with x_min, and those which are
greater than x_max, they get replaced with x_max.

Example 1:
1. import numpy as np
2. x= np.arange(12)
3. y=np.clip(x, 3, 10)
4. y

Output:

array([ 3, 3, 3, 3, 4, 5, 6, 7, 8, 9, 10, 10])

In the above code

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
o We have imported numpy with alias name np.

o We have created an array 'x' using arange() function.

o We have declared the variable 'y' and assigned the returned value
of clip() function.

o We have passed the array 'x', x_min, and x_max value in the function

o Lastly, we tried to print the value of 'y'.

In the output, a ndarray is shown, which contains elements ranging from 3 to 10.

Example 2:
1. import numpy as np
2. a = np.arange(12)
3. np.clip(a, 3, 9, out=a)
4. a

Output:

array([3, 3, 3, 3, 4, 5, 6, 7, 8, 9, 9, 9])
array([3, 3, 3, 3, 4, 5, 6, 7, 8, 9, 9, 9])

Example 3:
1. import numpy as np
2. a = np.arange(12)
3. np.clip(a, [3, 4, 1, 1, 1, 4, 4, 4, 4, 4, 5, 6], 8)

Output:

array([3, 4, 3, 3, 4, 5, 6, 7, 8, 8, 8, 8])

numpy.ndarray.flatten() in Python
In Python, for some cases, we need a one-dimensional array rather than a 2-D or
multi-dimensional array. For this purpose, the numpy module provides a function
called numpy.ndarray.flatten(), which returns a copy of the array in one
dimensional rather than in 2-D or a multi-dimensional array.

Syntax
1. ndarray.flatten(order='C')
Parameters:
order: {'C', 'F', 'A', 'K'}(optional)

If we set the order parameter to 'C', it means that the array gets flattened in row-
major order. If 'F' is set, the array gets flattened in column-major order. The array is
flattened in column-major order only when 'a' is Fortran contiguous in memory, and

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
when we set the order parameter to 'A'. The last order is 'K', which flatten the array
in same order in which the elements occurred in the memory. By default, this
parameter is set to 'C'.

Returns:
y: ndarray

This function returns a copy of the source array, which gets flattened into one-
dimensional.

Example 1:
1. import numpy as np
2. a = np.array([[1,4,7], [2,5,8],[3,6,9]])
3. b=a.flatten()
4. b

Output:

array([1, 4, 7, 2, 5, 8, 3, 6, 9])

In the above code

o We have imported numpy with alias name np.

o We have created a multi-dimensional array 'a' using array() function.

o We have declared the variable 'b' and assigned the returned value
of flatten() function.

o Lastly, we tried to print the value of 'b'.

In the output, it shows a ndarray, which contains elements of the multi-dimensional


array into 1-D.

Example 2:
1. import numpy as np
2. a = np.array([[1,4,7], [2,5,8],[3,6,9]])
3. b=a.flatten('C')
4. b

Output:

array([1, 4, 7, 2, 5, 8, 3, 6, 9])

In the above code

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
o We have imported numpy with alias name np.

o We have created a multi-dimensional array 'a' using array() function.

o We have declared the variable 'b' and assigned the returned value
of flatten() function.

o We have used 'C' order in the function.

o Lastly, we tried to print the value of 'b'.

In the output, it shows a ndarray, which contains elements of the multi-dimensional


array into 1-D.

Example 3:
1. import numpy as np
2. a = np.array([[1,4,7], [2,5,8],[3,6,9]])
3. b=a.flatten('F')
4. b

Output:

array([1, 2, 3, 4, 5, 6, 7, 8, 9])

Example 4:
1. import numpy as np
2. a = np.array([[1,4,7], [2,5,8],[3,6,9]])
3. b=a.flatten('A')
4. b

Output:

array([1, 4, 7, 2, 5, 8, 3, 6, 9])

Example 5:
1. import numpy as np
2. a = np.array([[1,4,7], [2,5,8],[3,6,9]])
3. b=a.flatten('K')
4. b

Output:

array([1, 4, 7, 2, 5, 8, 3, 6, 9])

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
numpy.meshgrid() in Python
The numpy module of Python provides meshgrid() function for creating a
rectangular grid with the help of the given 1-D arrays that represent the Matrix
indexing or Cartesian indexing. MATLAB somewhat inspires the meshgrid()
function. From the coordinate vectors, the meshgrid() function returns the
coordinate matrices.

In the above figure, the x-axis is ranging from -5 to 5, and the y-axis is ranging
from -5 to 5. So, there is a total of 121 points marked in the figure, each with x-
coordinate and y-coordinate. For any line parallel to the x-axis, the x-coordinates of
the marked points are -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, and 5 respectively. On the
other hand, for any line parallel to the y-axis, the y-coordinates of the marked
points from bottom to top are -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, and 5 respectively.

Syntax
1. numpy.meshgrid(*xi, **kwargs)
Parameters
x1, x2,…, xn : array_like

This parameter defines the 1-dimensional array, which represents the coordinates of
a grid.

indexing: {'xy', 'ij'}(optional)

This is an optional argument which defines the Cartesian 'xy'(by default) or matrix
('ij') indexing of output.

sparse: bool(optional)

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
This parameter is also optional. If we need a sparse grid for conserving memory, we
have to set this parameter to True. By default, it is set to False.

copy: bool(optional)

The aim of this optional argument is that it returns a copy of the original array for
conserving memory. By default, it is set to False.

If both sparse and copy parameters are set to False, then it will return non-
contiguous arrays. In addition, more than one element of a broadcast array can
refer to a single memory location. If we need to write into the arrays, then we have
to make copies first.

Returns
X1, X2, …, Xn

The coordinate length from the coordinate vector is returned from this function.

Example 1:
1. import numpy as np
2. na, nb = (5, 3)
3. a = np.linspace(1, 2, na)
4. b = np.linspace(1, 2, nb)
5. xa, xb = np.meshgrid(a, b)
6. xa
7. xb

Output:

array([[1. , 1.25, 1.5 , 1.75, 2. ],


[1. , 1.25, 1.5 , 1.75, 2. ],
[1. , 1.25, 1.5 , 1.75, 2. ]])
array([[1. , 1. , 1. , 1. , 1. ],
[1.5, 1.5, 1.5, 1.5, 1.5],
[2. , 2. , 2. , 2. , 2. ]])

In the above code

o We have imported numpy with alias name np.

o We have created two variables, i.e., na and nb, and assigned the values 5
and 3, respectively.

o We have created two arrays, i.e., a and b using linspace() function.

o After that, we have declared the variables 'xa' and 'xb' and assigned the
returned value of meshgrid()

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
o We have passed both the arrays 'a' and 'b' in the function

o Lastly, we tried to print the value of 'xa' and 'xb'.

In the output, two arrays have been shown which contain the coordinate length from
the coordinate vectors.

Example 2:
1. import numpy as np
2. na, nb = (5, 3)
3. a = np.linspace(1, 2, na)
4. b = np.linspace(1, 2, nb)
5. xa, xb = np.meshgrid(a, b, sparse=True)
6. xa
7. xb

Output:

array([[1. , 1.25, 1.5 , 1.75, 2. ]])


array([[1. ],
[1.5],
[2. ]])

Example 3:
1. import numpy as np
2. import matplotlib.pyplot as plt
3. a = np.arange(-10, 10, 0.1)
4. b = np.arange(-10, 10, 0.1)
5. xa, xb = np.meshgrid(a, b, sparse=True)
6. z = np.sin(xa**2 + xb**2) / (xa**2 + xb**2)
7. h = plt.contourf(a,b,z)
8. plt.show()

Output:

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
In the above code

o We have imported numpy with alias name np.

o We have imported matplotlib.pyplot as plt.

o We have created two arrays, i.e., a and b using np.arange() function.

o After that, we have declared the variables 'xa' and 'xb' and assigned the
returned value of meshgrid()

o We have passed both the arrays 'a' and 'b' in the function.

o After that, we have declared a variable z and assigned the return value of
np.sine() function.

o Lastly, we tried to draw contour lines and filled contours by using the
plt.contourf()

In the output, contour lines have been plotted.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Example 4:
1. import numpy as np
2. import matplotlib.pyplot as plt
3. a = np.linspace(-5, 5, 5)
4. b = np.linspace(-5, 5, 11)
5. random_data = np.random.random((11, 5))
6. xa, xb = np.meshgrid(a, b)
7. plt.contourf(xa, xb, random_data, cmap = 'jet')
8. plt.colorbar()
9. plt.show()

Output:

Example 5:
1. import numpy as np
2. import matplotlib.pyplot as plt
3. a = np.linspace(-5, 5, 5)

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
4. b = np.linspace(-5, 5, 11)
5. random_data = np.random.random((11, 5))
6. xa, xb = np.meshgrid(a, b)
7. sine = (np.sin(xa**2 + xb**2))/(xa**2 + xb**2)
8. plt.contourf(xa, xb, sine, cmap = 'jet')
9. plt.colorbar()
10. plt.show()

Output:

numpy standard deviation


The numpy module of Python provides a function called numpy.std(), used to
compute the standard deviation along the specified axis. This function returns the

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
standard deviation of the array elements. The square root of the average square
deviation (computed from the mean), is known as the standard deviation. By
default, the standard deviation is calculated for the flattened array. With the help of
the x.sum()/N, the average square deviation is normally calculated, and here,
N=len(x).

Standard Deviation=sqrt(mean(abs(x-x.mean( ))**2

Syntax:
1. numpy.std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<class
numpy._globals._NoValue>)
Parameters
a: array_like

This parameter defines the source array whose elements standard deviation is
calculated.

axis: None, int, or tuple of ints(optional)

It is the axis along which the standard deviation is calculated. The standard
deviation of the flattened array is computed by default. If it is a tuple of ints,
performs standard deviation over multiple axis instead of a single axis or all axis as
before.

dtype : data_type(optional)

This parameter defines the data type, which is used in computing the standard
deviation. By default, the data type is float64 for integer type arrays, and, for float
types array, it will be the same as the array type.

out : ndarray(optional)

This parameter defines the alternative output array in which the result is to be
placed. This alternative ndarray has the same shape as the expected output. But we
cast the type when necessary.

ddof : int(optional)

This parameter defines the Delta Degrees of Freedom. The N-ddof divisor is used in
calculations, where N is the number of elements. By default, the value of this
parameter is set to 0.

keepdims : bool(optional)

It is optional, whose value, when true, will leave the reduced axis as dimensions
with size one in the resultant. When it passes the default value, it will allow the non-
default values to pass via the mean method of sub-classes of ndarray, but the
keepdims will not pass. Also, the output or the result will broadcast against the input
array correctly.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Returns
This function will return a new array that contains the standard deviation. If we do
not set the 'out' parameter to None, it returns the output array's reference.

Example 1:
1. a=np.array([[1,4,7,10],[2,5,8,11]])
2. b=np.std(a)
3. b

Output:

3.391164991562634

In the above code

o We have imported numpy with alias name np.

o We have created an array 'a' via array() function.

o We have declared the variable 'b' and assigned the returned value
of std() function.

o We have passed the array 'a' in the function

o Lastly, we tried to print the value of 'b'.

In the output, an array containing standard deviation has been shown.

Example 2:
1. a=np.array([[1,4,7,10],[2,5,8,11]])
2. b=np.std(a, axis=0)
3. b

Output:

array([0.5, 0.5, 0.5, 0.5])

Example 3:
1. a=np.array([[1,4,7,10],[2,5,8,11]])
2. b=np.std(a, axis=1)
3. b

Output:

array([3.35410197, 3.35410197])

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Example 4:
1. import numpy as np
2. a = np.zeros((2, 512*512), dtype=np.float32)
3. a[1, :] = 1.0
4. a[0, :] = 0.1
5. b=np.std(a)
6. b

In the above code

o We have imported numpy with alias name np.

o We have created an array 'a' using np.zeros() function with data type
np.float32.

o We have assigned the value 0.1 to the elements of the 1st row and 1.0 to the
elements of the second row.

o We have passed the array 'a' in the function

o Lastly, we tried to print the value of 'b'.

In the output, the standard deviation has been shown, which can be inaccurate.

Output:

0.45000008

Example 5:
1. import numpy as np
2. a = np.zeros((2, 512*512), dtype=np.float32)
3. a[1, :] = 1.0
4. a[0, :] = 0.1
5. b=np.std(a ,dtype=np.float64))
6. b

Output:

0.4499999992549418

numpy.argmax in Python
In many cases, where the size of the array is too large, it takes too much time to
find the maximum elements from them. For this purpose, the numpy module of

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Python provides a function called numpy.argmax(). This function returns indices of
the maximum values are returned along with the specified axis.

Syntax:
1. numpy.argmax(a, axis=None, out=None)
Parameters
x: array_like

This parameter defines the source array whose maximum value we want to know.

axis: int(optional)

This parameter defines the axis along which the index is present, and by default, it
is into the flattened array.

out: array(optional)

This parameter defines the ndarray in which the result is going to be inserted. This
will be of the same type and shape, which is appropriate for storing the result

Returns
This parameter defines a ndarray, which contains the indices of the array. The shape
is the same as x.shape with the dimension along the axis removed.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Example 1:
1. Import numpy as np
2. x = np.arange(20).reshape(4,5) + 7
3. x
4. y=np.argmax(a)
5. y

Output:

array([[ 7, 8, 9, 10, 11],


[12, 13, 14, 15, 16],
[17, 18, 19, 20, 21],
[22, 23, 24, 25, 26]])
19

In the above code

o We have imported numpy with alias name np.

o We have created an array 'x' using np.arange() function with the shape of
four rows and five columns.

o We have added 7 in each element of the array also.

o We have declared the variable 'y' and assigned the returned value
of np.argmax() function.

o We have passed the array 'x' in the function.

o Lastly, we tried to print the value of 'y'.

In the output, it shows the indices of the maximum element in the array.

Example 2:
1. Import numpy as np
2. x = np.arange(20).reshape(4,5) + 7
3. y=np.argmax(x, axis=0)
4. z=np.argmax(x, axis=1)
5. y
6. z

Output:

array([3, 3, 3, 3, 3], dtype=int64)


array([4, 4, 4, 4], dtype=int64)

Example 3:
1. Import numpy as np

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
2. x = np.arange(20).reshape(4,5) + 7
3. indices = np.unravel_index(np.argmax(x, axis=None), x.shape)
4. indices
5. x[indices]

Output:

(3, 4)
26

Example 4:
1. import numpy as np
2. a = np.array([[5,2,1], [3,7,9],[0, 4, 6]])
3. index_arr = np.argmax(a, axis=-1)
4. index_arr
5. # Same as np.max(a, axis=-1, keepdims=True)
6. result = np.take_along_axis(a, np.expand_dims(index_arr, axis=-1), axis=-
1)
7. result1
8. # Same as np.max(a, axis=-1)
9. result = np.take_along_axis(a, np.expand_dims(index_arr, axis=-1), axis=-
1).squeeze(axis=-1)
10. result2

Output:

array([[0],
[2],
[2]])
array([5, 9, 6])

In the above code

o We have imported numpy with alias name np.

o We have created a multi-dimensional array 'a' using np.array() function.

o We have declared the variable 'index_arr' and assigned the returned value
of np.argmax() function.

o We have passed the array 'a' and the axis in the function.

o We tried to print the value of 'index_arr'.

o In the end, we tried to fetch the maximum value of the array with the help of
two different ways, which are quite similar to np.argmax().

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
In the output, it shows indices of the maximum elements in the array and the values
which are present on that indices.

numpy.diff() in Python
The numpy module of Python provides a function called numpy.diff for calculating
the nth discrete difference along the given axis. If 'x' is the input array, then the first
difference is given by out[i]=x[i+1]-a[i]. We can calculate the higher difference by
using diff recursively. The numpy module of Python provides a function called
numpy.diff for calculating the nth discrete difference along the given axis. If 'x' is
the input array, then the first difference is given by out[i]=x[i+1]-a[i]. We can
calculate the higher difference by using diff recursively.

Syntax
1. numpy.diff(a, n=1, axis=-1, prepend=<no value>, append=<no value>)
Parameters
x: array_like

This parameter defines the source array whose elements nth discrete deference are
those which we want to calculate.

n: int(optional)

This parameter defines the number of times the values are differenced. If it is 0,
then the source array is returned as it is.

append, prepend: array_like(optional)

This parameter defines a ndarray, which defines the values going to append or
prepend to 'x', along the axis before computing differences.

Returns:
This function returns a ndarray containing nth differences having the same shape
as 'x,' and the dimension is smaller from n. The type of difference between any two
elements of 'x' is the type of the output.

Example 1:
1. import numpy as np
2. arr = np.array([0, 1, 2], dtype=np.uint8)
3. arr
4. b=np.diff(arr)
5. b
6. arr[2,...] - arr[1,...] - arr[0,...]

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Output:

array([0, 1, 2], dtype=uint8)


array([1, 1], dtype=uint8)
1

In the above code

o We have imported numpy with alias name np.

o We have created an array 'arr' using np.array() function with the


dtype 'uint8'.

o We have declared the variable 'b' and assigned the returned value of
the np.diff() function.

o We have passed the array 'arr' in the function.

o Lastly, we tried to print the value of 'b' and the difference between elements.

In the output, it shows the discrete differences of elements.

Example 2:
1. import numpy as np
2. x = np.array([11, 21, 41, 71, 1, 12, 33, 2])
3. y = np.diff(x)
4. x
5. y

Output:

array([11, 21, 41, 71, 1, 12, 33, 2])


array([ 10, 20, 30, -70, 11, 21, -31])

Example 3:
1. import numpy as np
2. x = np.array([[11, 21, 41], [71, 1, 12], [33, 2, 13]])
3. y = np.diff(x, axis=0)
4. y
5. z = np.diff(x, axis=1)
6. z

Output:

array([[ 60, -20, -29],


[-38, 1, 1]])
array([[ 10, 20],
[-70, 11],
[-31, 11]])

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Example 4:
1. import numpy as np
2. x = np.arange('1997-10-01', '1997-12-16', dtype=np.datetime64)
3. y = np.diff(x)
4. y

Output:

array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1], dtype='timedelta64[D]')

In the above code

o We have imported numpy with alias name np.

o We have created an array of dates 'x' using np.arange() function with the
dtype 'datetime64'.

o We have declared the variable 'y' and assigned the returned value of
the np.diff() function.

o We have passed the array 'x' in the function.

o Lastly, we tried to print the value of 'y'.

In the output, it shows the discrete differences between dates.

numpy.histogram() in Python
The numpy module of Python provides a function called numpy.histogram(). This
function represents the frequency of the number of values that are compared with a
set of values ranges. This function is similar to the hist() function
of matplotlib.pyplot.

In simple words, this function is used to compute the histogram of the set of data.

Syntax:
1. numpy.histogram(x, bins=10, range=None, normed=None, weights=None, d
ensity=None)
Parameters:
x: array_like

This parameter defines a flattened array over which the histogram is computed.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
bins: int or sequence of str or scalars(optional)

If this parameter is defined as an integer, then in the given range, it defines the
number of equal-width bins. Otherwise, an array of bin edges which monotonically
increased is defined. It also includes the rightmost edge, which allows for non-
uniform bin widths. The latest version of numpy allows us to set bin parameters as a
string, which defines a method for calculating optimal bin width.

range : (float, float)(optional)

This parameter defines the lower-upper ranges of the bins. By default, the range
is (x.min(), x.max()). The values are ignored, which are outside the range. The
ranges of the first element should be equal to or less than the second element.

normed : bool(optional)

This parameter is the same as the density argument, but it can give the wrong
output for unequal bin widths.

weights : array_like(optional)

This parameter defines an array which contains weights and has the same shape
as 'x'.

density : bool(optional)

If it is set to True, will result in the number of samples in every bin. If its value is
False, the density function will result in the value of the probability density function
in the bin.

Returns:
hist: array

The density function returns the values of the histogram.

edge_bin: an array of float dtype

This function returns the bin edges (length(hist+1)).

Example 1:
1. import numpy as np
2. a=np.histogram([1, 5, 2], bins=[0, 1, 2, 3])
3. a

Output:

(array([0, 1, 1], dtype=int64), array([0, 1, 2, 3]))

In the above code

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
o We have imported numpy with alias name np.

o We have declared the variable 'a' and assigned the returned value
of np.histogram() function.

o We have passed an array and the value of the bin in the function.

o Lastly, we tried to print the value of 'a'.

In the output, it shows a ndarray that contain the values of the histogram.

Example 2:
1. import numpy as np
2. x=np.histogram(np.arange(6), bins=np.arange(7), density=True)
3. x

Output:

(array([0.16666667, 0.16666667, 0.16666667, 0.16666667, 0.16666667,


0.16666667]), array([0, 1, 2, 3, 4, 5, 6]))

Example 3:
1. import numpy as np
2. x=np.histogram([[1, 3, 1], [1, 3, 1]], bins=[0,1,2,3])
3. x

Output:

(array([0, 4, 2], dtype=int64), array([0, 1, 2, 3]))

Example 4:
1. import numpy as np
2. a = np.arange(8)
3. hist, bin_edges = np.histogram(a, density=True)
4. hist
5. bin_edges

Output:

array([0.17857143, 0.17857143, 0.17857143, 0. , 0.17857143,


0.17857143, 0. , 0.17857143, 0.17857143, 0.17857143])
array([0. , 0.7, 1.4, 2.1, 2.8, 3.5, 4.2, 4.9, 5.6, 6.3, 7. ])

Example 5:
1. import numpy as np
2. a = np.arange(8)
3. hist, bin_edges = np.histogram(a, density=True)
4. hist

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
5. hist.sum()
6. np.sum(hist * np.diff(bin_edges))

Output:

array([0.17857143, 0.17857143, 0.17857143, 0. , 0.17857143,


0.17857143, 0. , 0.17857143, 0.17857143, 0.17857143])
1.4285714285714288
1.0

In the above code

o We have imported numpy with alias name np.

o We have created an array 'a' using np.arange() function.

o We have declared variables 'hist' and 'bin_edges' and then assigned the
returned value of np.histogram() function.

o We have passed the array 'a' and set 'density' to True in the function.

o We tried to print the value of 'hist'.

o And lastly, we tried to calculate the sum of histogram values


using hist.sum() and np.sum() in which we passed histogram values and
edges of the bin.

In the output, it shows a ndarray that contains the values of the histogram and the
sum of histogram values.

numpy.matlib.eye()
This function returns a matrix with the diagonal elements initialized to 1 and zero
elsewhere.

Syntax
1. numpy.matlib.eye(n, m, k, dtype)
Parameters
It accepts the following parameters.

1. n: It represents the number of rows in the resulting matrix.

2. m: It represents the number columns in the resulting matrix.

3. k: It is the index of the diagonal.

4. dtype: It is the data type of the output.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Return
A matrix with uninitialized entries is returned.

Example
1. import numpy as np
2.
3. import numpy.matlib
4.
5. print(numpy.matlib.eye(n=3,m=3,k=0,dtype=int))

Output:

[[1 0 0]
[0 1 0]
[0 0 1]]

Example: Initializing float values


1. import numpy as np
2.
3. import numpy.matlib
4.
5. print(numpy.matlib.eye(n=3,m=3,k=0,dtype=float))

Output:

[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]

numpy.matlib.identity()
This function is used to return an identity matrix of the given size. An identity matrix
is the one with diagonal elements initializes to 1 and all other elements to zero.

Syntax
1. numpy.matlib.ones(size,dtype)
Parameters
It accepts the following parameters.

1. shape: It is the number of rows and columns in the resulting identity matrix.

2. dtype: It is the data type of the identity matrix.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Return
It returns an identity matrix of the specified size and specified data type.

Example
1. import numpy as np
2.
3. import numpy.matlib
4.
5. print(numpy.matlib.identity(4))

Output:

[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]

Example: Identity matrix with integer values


1. import numpy as np
2.
3. import numpy.matlib
4.
5. print(numpy.matlib.identity(4,int))

Output:

[[1 0 0 0]
[0 1 0 0]
[0 0 1 0]
[0 0 0 1]]

numpy.linspace()
It is similar to the arrange function. However, it doesn?t allow us to specify the step
size in the syntax.

Instead of that, it only returns evenly separated values over a specified period. The
system implicitly calculates the step size.

Syntax
1. numpy.linspace(start, stop, num, endpoint, retstep, dtype)

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Parameters
It accepts the following parameters.

1. start: It represents the starting value of the interval.

2. stop:It represents the stopping value of the interval.

3. num: The amount of evenly spaced samples over the interval to be


generated. The default is 50.

4. endpoint: Its true value indicates that the stopping value is included in the
interval.

5. rettstep: This has to be a boolean value. Represents the steps and samples
between the consecutive numbers.

6. dtype: It represents the data type of the array items.

Return
An array within the specified range is returned.

Example 1
1. import numpy as np
2. arr = np.linspace(10, 20, 5)
3. print("The array over the given range is ",arr)

Output:

The array over the given range is [10. 12.5 15. 17.5 20.]

Example 2
1. import numpy as np
2. arr = np.linspace(10, 20, 5, endpoint = False)
3. print("The array over the given range is ",arr)

Output:

The array over the given range is [10. 12. 14. 16. 18.]

numpy.logspace()
It creates an array by using the numbers that are evenly separated on a log scale.

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Syntax
1. numpy.logspace(start, stop, num, endpoint, base, dtype)
Parameters
It accepts the following parameters.

1. start: It represents the starting value of the interval in the base.

2. stop:It represents the stopping value of the interval in the base.

3. num:The number of values between the range.

4. endpoint:It is a boolean type value. It makes the value represented by stop


as the last value of the interval.

5. base:It represents the base of the log space.

6. dtype:It represents the data type of the array items.

Return
An array within the specified range is returned.

Example 1
1. import numpy as np
2. arr = np.logspace(10, 20, num = 5, endpoint = True)
3. print("The array over the given range is ",arr)

Output:

The array over the given range is [1.00000000e+10 3.16227766e+12


1.00000000e+15 3.16227766e+17 1.00000000e+20]

Example 2
1. import numpy as np
2. arr = np.logspace(10, 20, num = 5,base = 2, endpoint = True)
3. print("The array over the given range is ",arr)

Output:

The array over the given range is [1.02400000e+03 5.79261875e+03


3.27680000e+04 1.85363800e+05
1.04857600e+06]

INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT

You might also like