Numpy Notes
Numpy Notes
NumPy stands for numeric python which is a python package for the computation
and processing of the multidimensional and single dimensional array elements.
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.
5. NumPy provides the in-built functions for linear algebra and random number
generation.
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.
Redhat
On Redhat, the following commands are executed to install the Python SciPy
package stack.
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.
1. >>> a = numpy.array
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.
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
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.
To change the data type of the array elements, mention the name of the data type
along with the collection.
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.
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:
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:
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)
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.
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:
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:
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
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:
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]
Standard deviation means how much each element of the array varies from the
mean value of the numpy array.
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:
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:
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.
5 int8 It is the 8-bit integer identical to a byte. The range of the value is -12
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
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.
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.
INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
1. numpy.dtype(object, align, copy)
Align: It can be set to any boolean value. If true, then it adds extra padding to
make it equivalent to a C struct.
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
Example 1
1. import numpy as np
2. d = np.dtype([('salary',np.float)])
3. print(d)
Output:
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:
Numpy.empty
As the name specifies, The empty routine is used to create an uninitialized array of
specified shape and data type.
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.
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.
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.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.
Output:
<class 'numpy.ndarray'>
INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
[1 2 3 4 5 6 7]
Output:
<class 'numpy.ndarray'>
[1 2 3 4 5 6 7]
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.
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.
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.
2. stop: represents the value at which the interval ends excluding this value.
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:
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.
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.
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.
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:
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:
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.
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.
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.
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:
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.
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:
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:
[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]
[[ 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]]
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:
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
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:
[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]
INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
3 6 9 12 6 12 15 18 30 60 117 9
‘
SN Operator Description
1 bitwise_and It is used to calculate the bitwise and operation between the corr
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:
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.
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:
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.
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:
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:
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:
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:
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.]
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.
1. numpy.around(num, decimals)
SN Parameter Description
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:
Example
1. import numpy as np
2. arr = np.array([12.202, 90.23120, 123.020, 23.202])
3. print(np.floor(arr))
Output:
Example
1. import numpy as np
2. arr = np.array([12.202, 90.23120, 123.020, 23.202])
3. print(np.ceil(arr))
Output:
INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
Next →← Prev
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]]
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)
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]]
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.
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.
1 Quick Sort O (n ^ 2)
SN Parameter Description
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
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:
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.
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.
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:
numpy.nonzero() function
This function is used to find the location of the non-zero elements from the array.
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:
numpy.where() function
This function is used to return the indices of all the elements which satisfies a
particular condition.
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]))
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.
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
ID of b: 139663602288640
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.
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
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.
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
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.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.
Example
1. import numpy as np
2.
3. import numpy.matlib
4.
5. print(numpy.matlib.empty((3,3)))
Output:
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.
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.
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.
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.
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.
Example
1. import numpy as np
2.
3. import numpy.matlib
4.
5. print(numpy.matlib.rand(3,3))
Output:
SN Function Definition
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]]
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.
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
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.
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
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.
1. 3X + 2 Y + Z = 10
2. X + Y + Z = 5
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]]
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.
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.
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 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:
Output:
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().
In the output, a three-dimensional matrix has been shown whose elements are the
product of both array1 and array2 elements.
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 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
o We have created a variable result and assigned the returned value of the
np.dot() function.
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:
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.
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.
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.
'A' Unchanged When the input is F and not C then F order otherwise
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)
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])
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.
Example 2:
1. import numpy as np
2. arr=np.array([1,2.,3.])
3. arr
Output:
o We have declared the 'arr' variable and assigned the value returned by
np.array() function.
In the output, an array has been displayed containing elements in such type which
require minimum memory to hold the object in the sequence.
Output:
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.
Output:
o We have declared the 'arr' variable and assigned the value returned by
np.array() function.
Output:
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.
In the output, the values of the 'arr' elements have been shown in the form of
complex numbers.
Output:
array([[1, 2],
[3, 4]])
matrix([[1, 2],
[3, 4]])
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.
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:
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.
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
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.
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]])
Output:
array([[ 1, 2],
[ 3, 4],
[12, 30]])
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.
Output:
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
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.
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:
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])
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.
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.
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.
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:
Output:
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.
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.
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.
Output:
INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
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.
In the output, the array has been represented as three rows and four columns.
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:
Output:
INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
[ 3, 7, 11]])
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.
In the output, the array has been represented as four rows and three columns.
Output:
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.
In the output, the array has been represented as two rows and five columns.
Output:
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:
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.
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
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
o We have declared variable 'b' and assigned the returned value of np.sum()
function.
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:
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.
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
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
o We have declared variable 'b' and assigned the returned value of np.sum()
function.
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
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.
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.
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]])
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:
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])
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])
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)
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:
2) np.random.permutation()
Example:
1. import numpy as np
2. a=np.random.permutation(12)
3. a
Output:
Distributions
There are the following functions of permutations:
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()
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])
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])
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])
Example:
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
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:
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])
Example:
1. import numpy as np
2. a = np.random.geometric(p=0.35, size=10000)
3. (a == 1).sum() / 1000
Output:
3.
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:
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>)
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:
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:
INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
13) lognormal([mean, sigma, size])
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:
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])
Example:
1. import numpy as np
2. np.random.multinomial(20, [1/6.]*6, size=1)
Output:
array([[4, 2, 5, 5, 3, 1]])
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:
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:
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])
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:
Example:
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])
Example:
1. import numpy as np
2. n = np.random.standard_exponential((2, 7000))
Output:
25) standard_gamma([size])
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])
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:
[[-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]]])
This function is used to draw sample from a standard Student's distribution with df
degree of freedom.
Example:
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])
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])
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])
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:
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.
Output:
INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
array([0., 0., 0., 0., 0., 0.])
o We have declared the variable 'a' and assigned the returned value of
np.zeros() function.
Output:
array([0, 0, 0, 0, 0, 0])
Output:
array([[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.]])
o We have declared the variable 'a' and assigned the returned value of
np.zeros() function.
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.]])
Output:
array([(0, 0), (0, 0), (0, 0)], dtype=[('x', '<i4'), ('y', '<i4')])
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.
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.
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.
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)
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 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:
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 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:
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.
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.
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:
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
o We have declared the variable 'b' and assigned the returned value of
np.where() function.
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:
INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
4. b
Output:
array([[1, 8],
[3, 4]])
Output:
o We declared the variable 'b' and assigned the returned value of np.where()
function.
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.
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 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.
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.
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
o We have declared the variable 'b' and assigned the returned value of
np.argsort() function.
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:
Output:
array([[0, 1],
[1, 0]], dtype=int64)
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 Next, we used the take_along_axis() function and passed the source array,
indices, and axis.
In the output, a 2-D array with sorted elements has been shown.
Output:
array([[0, 2],
[3, 5]])
Output:
array([[0, 1],
[1, 0]], dtype=int64)
Output:
array([[0, 2],
[3, 5]])
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])
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.
In the output, an N-D array with sorted elements has been shown.
Output:
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.
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
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]])
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.
In the output, the transposed array of the original array has been shown.
Output:
array([[1, 2],
[4, 5],
[7, 8]])
array([[1, 4, 7],
[2, 5, 8]])
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.
In the output, the transposed array of the original array has been shown.
INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
6. c
Output:
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.
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.
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
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.
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
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'.
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'.
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])
o We have declared the variable 'a' and assigned the returned value of
np.unique() function.
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]])
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.
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:
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.
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.
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:
o We have declared the variable 'a_list' and assigned the returned value of
the list() function.
o We have declared the variable a_tolist and assigned the returned value
of ndarray.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]]
o We have declared the variable 'b' and assigned the returned value
of a.tolist() function.
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:
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.
a: array_like
b: array_like
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]])
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'.
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
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
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:
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.
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.
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:
o We have declared the variable 'c' and assigned the returned value of the
StringIO() function.
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:
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.])
o We have declared the variable 'c' and assigned the returned value of the
StringIO() 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.
This parameter defines the minimum value for clipping values. On the lower interval
edge, clipping is not required.
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:
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 '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
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])
o We have declared the variable 'b' and assigned the returned value
of flatten() function.
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])
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 'b' and assigned the returned value
of flatten() function.
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.
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:
o We have created two variables, i.e., na and nb, and assigned the values 5
and 3, respectively.
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
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:
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 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()
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:
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).
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.
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
o We have declared the variable 'b' and assigned the returned value
of std() function.
Example 2:
1. a=np.array([[1,4,7,10],[2,5,8,11]])
2. b=np.std(a, axis=0)
3. b
Output:
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
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.
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:
o We have created an array 'x' using np.arange() function with the shape of
four rows and five columns.
o We have declared the variable 'y' and assigned the returned value
of np.argmax() function.
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:
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])
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 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.
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:
o We have declared the variable 'b' and assigned the returned value of
the np.diff() function.
o Lastly, we tried to print the value of 'b' and the difference between 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:
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:
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]')
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.
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.
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
Example 1:
1. import numpy as np
2. a=np.histogram([1, 5, 2], bins=[0, 1, 2, 3])
3. a
Output:
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.
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:
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:
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:
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:
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.
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.
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]]
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.
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.]]
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.
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.
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.
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:
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:
INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT
INTE 316. NUMERICAL ANALYSIS AND PROGRAMMMING- NUMPY NOTES - COMPILED BY KIPKEBUT