Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

NumPy Library and Function

You are on page 1of 129

NumPy Library

1. NumPy is a Python library used for working with arrays.


2. It also has functions for working in domain of linear algebra, fourier
transform, and matrices.
3. NumPy was created in 2005 by Travis Oliphant. It is an open source
project and you can use it freely.
4. NumPy stands for Numerical Python.
The need of
NumPy
With the revolution of data science, data analysis libraries like NumPy, SciPy, Pandas, etc. have
seen a lot of growth. With a much easier syntax than other programming languages, python is the
first choice language for the data scientist.
NumPy provides a convenient and efficient way to handle the vast amount of data. NumPy is also
very convenient with Matrix multiplication and data reshaping. NumPy is fast which makes it
reasonable to work with a large set of data.
There are the following advantages of using NumPy for data analysis.
1.NumPy performs array-oriented computing.
2.It efficiently implements the multidimensional arrays.
3.It performs scientific computations.
4.It is capable of performing Fourier Transform and reshaping the data stored in
multidimensional arrays.
5.NumPy provides the in-built functions for linear algebra and random number
Installation of NumPy
If you have Python and PIP already installed on a system, then installation

of NumPy is very easy.

Install it using this command:


C:\Users\Your Name>pip install

C:\Users\Your Name>pip install numpy


Import NumPy

Once NumPy is installed, import it in your applications by adding


the import keyword:

import numpy

arr = numpy.array([1, 2, 3, 4, 5])

print(arr)
NumPy as np
NumPy is usually imported under the np alias.
alias: In Python alias are an alternate name for referring to the same
thing.

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr)
Create a NumPy ndarray Object

NumPy is used to work with arrays. The array object in NumPy is


called ndarray.
We can create a NumPy ndarray object by using the array() function.
import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr)

print(type(arr))

Output
[1 2 3 4 5]
<class 'numpy.ndarray'>
Dimensions in Arrays

A dimension in arrays is one level of array depth (nested arrays).

We can also pass a collection object into the array routine to create the
equivalent n-dimensional array. The syntax is given below.
>>> numpy.array(object, dtype = None, copy = True, order = None, su
bok = False, ndmin = 0)
The parameters are described in the following table.
SN Parameter Description
1 object It represents the collection object. It can be a list, tuple, dictionary,
set, etc.

2 dtype We can change the data type of the array elements by changing this
option to the specified type. The default is none.

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

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


(column order), R (row order), or A (any)

The returned array will be base class array by default. We can change
5 subok this to make the subclasses passes through by setting this option to
true.

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


To create an array using the list, use the following syntax
.
>>> arr= numpy.array([1, 2, 3])

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr)

print(type(arr))
Output
[1 2 3 4 5]
<class 'numpy.ndarray'>
Dimensions of Array
0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an
array is a 0-D array.

import numpy as np

arr = np.array(42)

print(arr)

Output
42
1-D Arrays
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.
These are the most common and basic arrays.

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr)

Output
[1 2 3 4 5]
2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.
These are often used to represent matrix or 2nd order tensors.
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

print(arr)

[[1 2 3]
[4 5 6]]
3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array.

import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]],


[[1, 2, 3], [4, 5, 6]]])

print(arr)

Output
[[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]]
Check Number of Dimensions?
NumPy Arrays provides the ndim attribute that returns an integer that tells
us how many dimensions the array have.
import numpy as np

a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(a.ndim)
print(b.ndim)
print(c.ndim) Output
print(d.ndim)
0
1
2
3
Higher Dimensional Arrays
An array can have any number of dimensions.
When the array is created, you can define the number of dimensions by using the ndmin argument.

import numpy as np

arr = np.array([1, 2, 3, 4], ndmin=5)

print(arr)
print('number of dimensions :', arr.ndim)

[[[[[1 2 3 4]]]]] number of


dimensions : 5
Anatomy of an array :
1. Axis: The Axis of an array describes the order of the
indexing into the array.
Axis 0 = one dimensional
Axis 1 = Two dimensional
Axis 2 = Three dimensional
2. Shape: The number of elements along with each axis. It
is from a tuple.
# importing numpy module
import numpy as np
# creating list
list_1 = [1, 2, 3, 4]
list_2 = [5, 6, 7, 8]
list_3 = [9, 10, 11, 12]
# creating numpy array
sample_array = np.array([list_1, list_2, list_3])
print("Numpy array :")
print(sample_array)
Output:
# print shape of the array Numpy array :
print("Shape of the array :", sample_array.shape) [[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
Shape of the array : (3,
Reshaping the array objects
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.
import numpy as np
a = np.array([[1,2],[3,4],[5,6]])
print("printing the original array.
.")
print(a)
a=a.reshape(2,3)
print("printing the reshaped arr
ay..") Output:
print(a) printing the original array..
[[1 2]
[3 4]
[5 6]]
printing the reshaped array..
[[1 2 3]
[4 5 6]]
Data type objects (dtype):
Data type objects (dtype) is an instance of numpy.dtype class. It
describes how the bytes in the fixed-size block of memory
corresponding to an array
# Import item should be interpreted.
module
import numpy as np
# Creating the array
sample_array_1 = np.array([[0, 4, 2]])
sample_array_2 = np.array([0.2, 0.4, 2.4])
# display data type
print("Data type of the array 1 :", sample_array_1.dtype)
print("Data type of array 2 :",sample_array_2.dtype)

Output:
Data type of the array 1 : int32
Data type of array 2 : float64
Integer
Yype Bytes Range
np.int8 1 -128 to 127
np.int16 2 -32768 to 32767
np.int32 4 -2147483648 to 2147483647
np.int64 8 -9223372036854775808 to
9223372036854775807

Unsigned integers
Unsigned integers are similar to normal integers, but they can only hold non-zero values. Here are the
available types:

Type Bytes Range


np.uint8 1 0 to 255
np.uint16 2 0 to 65535
np.uint32 4 0 to 4294967295
np.uint64 8 0 to 18446744073709551615
Floats
numpy floating point numbers also have different sizes
(usually called precisions). There are two types:

Type Bytes Range Precision


np.float32 4 ±1.18×10−38 to ±3.4×1038 7 to 8 decimal digits
np.float64 8 ±2.23×10−308 to ±1.80×10308 15 to 16 decimal digits
Operations on Numpy
Creating NumPy Array
We can create a NumPy array using various function
provided by the Python NumPy library.
This package provides a multidimensional array object
and various other required objects, routines, for
efficient functionality.
Following are the functions using which we can create
a NumPy array −
•Using numpy.array() Function
•Using numpy.zeros() Function
•Using numpy.ones() Function
•Using numpy.arange() Function
•Using numpy.linspace() Function
•Using numpy.random.rand() Function
•Using numpy.empty() Function
•Using numpy.full() Function
Using numpy.zeros() Function
We can also use the numpy.zeros() function for creating an array by specifying the desired
shape of the array as a tuple or an integer.
This function creates a NumPy array filled with zeros. It accepts the shape of the array as an
argument and optionally the data type (dtype). By default, the data type is float64.
Following is the syntax −

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

import numpy as np # Creating an array ofzeros


arr = np.zeros(5)
print(arr)
Following is the output of the above code −
[0. 0. 0. 0. 0.]
Using numpy.ones() Function
On the other hand, the numpy.ones() function creates an array where all elements are set to 1 .
It accepts three main parameters: shape, dtype, and order.
•The shape parameter, which can be an integer or a tuple of integers, defines the dimensions of the
array.
•The dtype parameter specifies the desired data type of the array elements, defaulting to "float64" if
not provided.
•The order parameter determines the memory layout of the array, either row-major (C-style) or
column-major (Fortran-style), with 'C' being the default.

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

import numpy as np # Creating an array of ones


arr = np.ones(3)
print(arr)
Output
[1. 1. 1.]
Using numpy.arange() Function
The numpy.arange() function creates an array by generating a sequence of numbers based on
specified start, stop, and step values. It is similar to Python's built-in range() function.
This function creates an array of evenly spaced values within a given interval.
It allows specifying the start, stop, and step size, and returns a NumPy array.
•start − The starting value of the sequence. If not specified, it defaults to 0.
•stop − The end value of the sequence. This value is exclusive, meaning it is not included in the
sequence.
•step − The step or interval between each pair of consecutive values in the sequence. If not
specified, it defaults to 1.
numpy.arange([start,] stop[, step,] dtype=None, *, like=None)

import numpy as np # Providing just the stop value


array1 = np.arange(10)
print("array1:", array1) # Providing start, stop and step value
array2 = np.arange(1, 10, 2)
print("array2:",array2)
Output
array1: [0 1 2 3 4 5 6 7 8 9]
array2: [1 3 5 7 9]
Using numpy.linspace() Function
We can even use the numpy.linspace() function to create an array by specifying the start, stop,
and the number of elements we want.

numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,


axis=0)

In the example below, we are using numpy.linspace() function to create three arrays
(array1, array2, and array3) with specified ranges and configurations.
The "array1" is created with 10 evenly spaced values from 0 to 5, inclusive.
The "array2 consists of 5 values ranging from 1 to just under 2, excluding the endpoint.
The "array3" is created with 5 values from 0 to 10, and returns both the array and the step size
between consecutive values −
import numpy as np # Creating an array of 10 evenly spaced
values from 0 to 5
array1 = np.linspace(0, 5, num=10)
print("array1:",array1)
array2 = np.linspace(1, 2, num=5, endpoint=False)
print("array2:",array2) # Creating an array and returning the
step value
array3, step = np.linspace(0, 10, num=5, retstep=True)
print("array3:",array3)
print("Step size:", step)
1: [0. 0.55555556 1.11111111 1.66666667 2.22222222 2.77777778 3.3333
44444 5. ]
2: [1. 1.2 1.4 1.6 1.8]
3: [ 0. 2.5 5. 7.5 10. ]
size: 2.5
random.rand() Function
Alternatively, we can use the numpy.random.rand() function for creating an array by specifying
the dimensions of the array as parameters.

numpy.random.rand(d0, d1, ..., dn)

import numpy as np # Generating a single random float


random_float = np.random.rand()
print("random_float:",random_float) # Generating a 1D array of random floats
array_1d = np.random.rand(5)
print("array_1d:",array_1d) # Generating a 2D array of random floats
array_2d = np.random.rand(2, 3)
print("array_2d:",array_2d) # Generating a 3D array of random floats
array_3d = np.random.rand(2, 3, 4)
print("array_3d:",array_3d)
random_float: 0.5030496450079744
array_1d: [0.19476581 0.54430648 0.64571106 0.27443774 0.71874319]
array_2d: [[0.91141582 0.58847504 0.37284854]
[0.0715398 0.21305363 0.766954 ]]
array_3d: [[[0.7295106 0.1582053 0.91376381 0.14099229] [0.6876814
0.19351871 0.18056163 0.61370308] [0.42382443 0.6665121
0.42322218 0.11707395]] [[0.60883975 0.01724199 0.95753734
0.17805716] [0.47770594 0.55840874 0.7375783 0.50512301]
[0.73730351 0.85900855 0.16472072 0.2338285 ]]]
Using numpy.empty() Function
We can create a NumPy array using the numpy.empty() function by specifying the shape of the
array as parameters

Unlike numpy.zeros() function and numpy.ones() function, which initialize array elements to zero
and one respectively, the numpy.empty() function does not initialize the elements. Instead, it
allocates the memory required for the array without setting any values.

import numpy as np empty_array =


np.empty((2, 3))
print(empty_array)

[[1.13750619e-313 0.00000000e+000 0.00000000e+000]


[0.00000000e+000 0.00000000e+000 0.00000000e+000]]
Using numpy.full() Function
Using the numpy.full() function, we can create an array with a desired shape and set all the elements
in it to a specific value. Following is the syntax −

numpy.full(shape, fill_value, dtype=None, order='C')

In the following example, we are using the numpy.full() function to create a 2-dimensional array with
dimensions 2x3, filled entirely with the value 5 −

import numpy as np array1 = np.full((2, 3), 5)


print(array1)

Output
[[5 5 5]
[5 5 5]]
Array Manipulation
Changing Shape

In NumPy, to change shape is to alter the shape of arrays without changing their data −

Sr.No. Shape & Description

1 reshapeGives a new shape to an array without changing its


data
2 flatA 1-D iterator over the array

3 flatten Returns a copy of the array collapsed into one


dimension
4 ravel Returns a contiguous flattened array
The Numpy reshape() Function is used to change the shape of an array
without altering its data. It returns a new view or array with the specified
dimensions, provided the total number of elements remains constant.
Syntax
The syntax for the Numpy reshape() function is as follows −

numpy.reshape(arr, newshape, order='C')


Parameters
Following are the parameters of the Numpy reshape() Function −
•arr: The input array that has to be reshaped.
•newshape: This parameter can be int or tuple of int. New shape should
be compatible to the original shape.
•order: This parameter defines read and write order. If 'C' for row-major,
'F' for column-major.
import numpy as np # Create a 1D array with 8 elements
a = np.arange(8)
print('The original array:')
print(a) print('\n') # Reshape the array to a 2D array with shape (4, 2)
b = a.reshape(4, 2)
print('The modified array:') print(b)

Output
The original array: [0 1 2 3 4 5 6 7]
The modified array:
[[0 1]
[2 3]
[4 5]
[6 7]]
The Numpy ndarray.flat Attribute which returns a 1-D iterator over the
array.
This iterator allows us to iterate over the array as if it were flattened but it
does not create a new array.
Syntax
Here is the syntax of Numpy ndarray.flat() Attribute −

numpy.ndarray.flat
import numpy as np # Creating a 2D numpy array
array_2d = np.array([[1, 2, 3], [4, 5, 6]]) # Using flat to
1
iterate over elements
2
for item in array_2d.flat: 3
4
print(item)
5
6
import numpy as np # Creating a 2D numpy array
array_2d = np.array([[1, 2, 3], [4, 5, 6]]) # Modifying elements using flat
iterator

for index, value in enumerate(array_2d.flat):


array_2d.flat[index] = value * 2
print(array_2d)

Output
[[ 2 4 6]
[ 8 10 12]]
import numpy as np # Creating a 3D numpy array
array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
# Accessing specific elements using flat
print(array_3d.flat[0]) # First element
print(array_3d.flat[5]) # Sixth element
print(array_3d.flat[-1]) # Last element

Output
1
6
8
The Numpy ndarray.flatten()method which is used to return a new 1-
D array that is a copy of the original array which is flattened.
The ndarray.flat attribute which is an iterator
and ndarray.flatten() which creates a new array.
Syntax
The syntax for the Numpy ndarray.flatten function is as follows −

ndarray.flatten(order='C')

Parameter
This function takes a single parameter i.e. 'C' which is row major which
is by default.
We can assign 'F': column major, 'A': flatten in column-major order, if a
is Fortran contiguous in memory, row-major order otherwise 'K': flatten
a in the order the elements occur in the memory
Example 1
import numpy as np # Creating a 2D numpy array
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
# Flattening the array using the default order ('C')
flattened_array = array_2d.flatten()
print("Original 2D array:")
print(array_2d)
print("\n Flattened array (row-major order):")
print(flattened_array)
Output
Original 2D array:
[[1 2 3]
[4 5 6]]
Flattened array (row-major order):
[1 2 3 4 5 6]
Example 2
Here in this example we show how a 3D array is flattened into a 1D
array in column-major order which yields [1, 5, 3, 7, 2, 6, 4, 8] −
import numpy as np # Creating a 3D numpy array
array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
# Flattening the array using the 'F' order
flattened_array = array_3d.flatten(order='F')
print("Original 3D array:")
print(array_3d)
print("\nFlattened array (column-major order):")
print(flattened_array) Output
Original 3D array:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
Flattened array (column-major order):
[1 5 3 7 2 6 4 8]
Example 3
Below example shows flattening a Fortran-contiguous array using the 'A'
order which results in column-major order flattening, giving [1, 4, 2, 5, 3,
6] −

import numpy as np # Creating a 2D numpy array with Fortran-


contiguous memory layout
array_fortran = np.asfortranarray([[1, 2, 3], [4, 5, 6]])
# Flattening the array using the 'A' order
flattened_array = array_fortran.flatten(order='A')
print("Original Fortran-contiguous 2D array:")
print(array_fortran) Output
print("\nFlattened array ('A' order):") Original Fortran-contiguous 2D
print(flattened_array) array:
[[1 2 3]
[4 5 6]]
Flattened array ('A' order):
[1 4 2 5 3 6]
The Numpy ravel() Function returns a flattened array by providing a 1-D
array containing the same elements as the input but with only one
dimension.
When compared to flatten() function the ravel() returns a flattened view
of the input array
numpy.ravel(a, whenever possible and if the input array is not
order='C')
contiguous then it returns a copy.
Parameters
Following are the parameters of Numpy ravel() Function −
•a (array_like): The elements in 'a' are read in row-major (C-style)
order or column-major (Fortran-style) order depending on the order
parameter.
•order: {'C', 'F', 'A', 'K'}, optional :Specifies the order in which the
elements are read.
• 'C': Row-major (C-style) order.
• 'F': Column-major (Fortran-style) order.
• 'A': For row-major order if the array is stored in row-major
memory order and column-major order otherwise.
• 'K': The elements are read in the order they occur in memory,
except for reversing the data when strides are negative.
Return Value
This function returns a 1-D array containing the elements of the input
array in a flattened order.
Example 1
Following is the example of Numpy ravel() Function which shows the
basic use of ravel() to flatten a 2D array into a 1D array in row-major
order.
import numpy as np # Creating a 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6]]) Output
# Flattening the array Original array:
flattened_array = np.ravel(array_2d) [[1 2 3]
print("Original array:\n") [4 5 6]]
print(array_2d) Flattened array:
print("Flattened array:") print(flattened_array) [1 2 3 4 5 6]
Example 2
Here this example illustrates the use of numpy.ravel() function to flatten a 3D array into
a 1D array, following the default row-major order.

import numpy as np # Creating a 3D array


array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
# Flattening the array
flattened_array_3d = np.ravel(array_3d) Output
print("Original 3D array:\n") Original 3D array:
print(array_3d) [[[1 2]
print("Flattened array:") [3 4]]
print(flattened_array_3d) [[5 6]
[7 8]]]
Flattened array:
[1 2 3 4 5 6 7 8]
Joining Arrays
Joining arrays in NumPy concatenate multiple arrays along specified axes −

Sr.N
Array & Description
o.
1 concatenate Joins a sequence of arrays along an existing axis
2 stack Joins a sequence of arrays along a new axis
3 hstack Stacks arrays in sequence horizontally (column wise)
4 vstack Stacks arrays in sequence vertically (row wise)
The Numpy Concatenate() Function is used to join a sequence of
arrays along an existing axis. This function takes a tuple or list of arrays
to concatenate and an optional axis parameter that specifies the axis
along which the arrays will be joined.
numpy.concatenate((a1, a2, ...),axis=0,out=None,dtype=None, casting="same_kind")
Parameters
Following are the parameters of the Numpy concatenate() function −
•a1, a2, ...: array_like : These are the arrays to be concatenated. They must
have the same shape, except in the dimension corresponding to axis.
•axis(int, optional): The axis along which the arrays will be joined. The default
is 0. If axis is None, the arrays are flattened before use.
•out(ndarray, optional): If provided, the destination to place the result. It must
have the right shape to hold the output.
•dtype(data-type, optional): The type to use in the output array. By default,
the dtype will be inferred from the inputs.
•casting({'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional): Controls
what kind of data casting may occur. Defaults to 'same_kind'.
Example 1
Following is the example of Numpy Concatenate() Function which
demonstrates concatenating two 1-D arrays along the default axis
(axis=0), resulting in a single 1-D array −

import numpy as np # Define two 1-D arrays


array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
# Concatenate along the default axis (axis=0)
result = np.concatenate((array1, array2))
print("Result of concatenation:", result)
Output
Result of concatenation: [1 2 3 4 5 6]
Example 2
Here in the below example we show how to concatenate two 2-D
arrays along the rows (axis=0), resulting in a single 2-D array with
more rows.
import numpy as np # Define two 2-D arrays
array1 = np.array([[1, 2], [3, 4]])
array2 = np.array([[5, 6], [7, 8]])
# Concatenate along axis 0 (rows)
result = np.concatenate((array1, array2), axis=0)
print("Result of concatenation along axis 0:", result)

Result of concatenation along axis 0:


[[1 2]
[3 4]
[5 6]
[7 8]]
Example 3
We can concatenate two 2-D arrays along the columns by defining
axis=1 in the concatenate() function, resulting in a single 2-D array with
more columns. Below is the example of it −

import numpy as np # Define two 2-D arrays


array1 = np.array([[1, 2], [3, 4]])
array2 = np.array([[5, 6], [7, 8]])
# Concatenate along axis 1 (columns)
result = np.concatenate((array1, array2), axis=1)
print("Result of concatenation along axis 1:", result)

Output
Result of concatenation along axis 1:
[[1 2 5 6]
[3 4 7 8]]
The Numpy stack() Function is used to join a sequence of arrays along
a new axis. All input arrays must have the same shape.
This function is useful for combining arrays of the same shape along a
specified dimension while creating a new dimension in the output array.
For example, stacking two 2D arrays along a new axis creates a 3D
array.

numpy.stack(arrays, axis=0, out=None, *, dtype=None, casting='same_kind')

Parameters
•arrays: These are the arrays you want to stack. All arrays must have the same shape.
•axis: The axis along which the arrays will be stacked. It must be between 0 and the number of
dimensions of the input arrays.
•out: If provided, the destination to place the result. It should be of the appropriate shape and
dtype.
•dtype: If provided, the dtype to use for the resulting array.
•casting: Controls what kind of data casting may occur.
Example 1
Following is the basic example of using Numpy stack() Function. In this
example the two 1-D arrays are stacked along a new axis, resulting in a 2-
D array

import numpy as np
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
stacked_array = np.stack((array1, array2))
print("Stacked Array:\n", stacked_array)
Output
Stacked Array:
[[1 2 3]
[4 5 6]]
Example 2
This is another example of using the stack() function, here in this example
two 2-D arrays are stacked along axis 1 which results in a 3-D array −

import numpy as np
array1 = np.array([[1, 2], [3, 4]])
array2 = np.array([[5, 6], [7, 8]])
stacked_array = np.stack((array1, array2), axis=1)
print("Stacked Array:\n", stacked_array)
Output
Stacked Array:
[[[1 2]
[5 6]]
[[3 4]
[7 8]]]
Example 3
Here in ths example two 3-D arrays are stacked along axis 2, resulting in
a 4-D array −

import numpy as np
array1 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
array2 = np.array([[[9, 10], [11, 12]], [[13, 14], [15, 16]]])
stacked_array = np.stack((array1, array2), axis=2)
print("Stacked Array:\n", stacked_array) Stacked Array:
[[[[ 1 2]
[ 9 10]]
[[ 3 4]
[11 12]]]
[[[ 5 6]
[13 14]]
[[ 7 8]
[15 16]]]]
The Numpy hstack() Function which is used to horizontally stack arrays. It
combines a sequence of arrays along their horizontal axis i.e. axis 1.
All input arrays must have the same number of rows or compatible shapes
for broadcasting and the function returns a new array with columns
concatenated.

numpy.hstack(tup, *, dtype=None, casting='same_kind')


Parameters
Following are the parameters of the Numpy hstack() Function −
•tup: A tuple of arrays to be stacked. The arrays must have the same
shape along all but the second axis.
•dtype: This parameter specifies the data type of the resulting array. If
provided all input arrays are cast to this data type before stacking. If
None the data type is determined from the input arrays.
•casting: This parameter Controls the type casting rule if dtype is
specified. It determines how the data types are handled when converting
to dtype
Example 1
Following is the example of Numpy hstack() function which shows how
two 1D arrays are concatenated into a single 1D array.
import numpy as np # CreatinG two 1D arrays
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
# Stacking arrays horizontally
result = np.hstack((array1, array2))
print(result)
Output
[1 2 3 4 5 6]
Example 2
This example shows how a 1D array is reshaped and stacked with a 2D
array, demonstrating the flexibility of numpy.hstack() with mixed
dimensions −
import numpy as np # Creating a 2D array and a 1D array
array1 = np.array([[1, 2, 3], [4, 5, 6]])
array2 = np.array([7, 8]) # Reshape array2 to be a column
vector with the same number of rows as array1 # Note:
array2 needs to have the same number of rows as array1 for
successful horizontal stacking
array2 = np.array([7, 8]).reshape(-1, 1) # Reshape to (2,
1) to match the number of rows in array1 # Stack arrays
horizontally
result = np.hstack((array1, array2))
print("Resulting Array:")
print(result)
Output
Resulting Array: .
[[1 2 3 7]
[4 5 6 8]]
Example 3
Here in this example we are combining two arrays into 1 single array −

import numpy as np # Define the first array


a = np.array([[1, 2], [3, 4]])
print('First array:')
print(a)
print('\n')
# Define the second array
b = np.array([[5, 6], [7, 8]])
print('Second array:')
print(b) print('\n')
# Horizontally stack the two arrays
c = np.hstack((a, b))
print('Horizontal stacking:')
print(c)
print('\n')
First array:
[[1 2]
[3 4]]
Second array:
[[5 6]
[7 8]]
Horizontal stacking:
[[1 2 5 6]
[3 4 7 8]]
The Numpy vstack() function stacks arrays vertically (row-wise). It takes
a sequence of arrays and concatenates them along the vertical axis i.e.
axis 0.
This function is particularly useful for combining arrays of the same
number of columns but different rows. The arrays should have the same
number of columns to be stacked
numpy.vstack(tup)
Parameter
The Numpy vstack() function takes a single parameter
namely, tup which is a sequence of 1-D or 2-D arrays. All arrays must have
the same shape along all but the first axis. 1-D arrays must have the same
length.
Return Value
This function returns a single 2-D array formed by stacking the given arrays
Example 1
Following is the example of Numpy vstack() function which shows
stacking two 1-D arrays vertically to form a 2-D array −

import numpy as np
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
result = np.vstack((array1,
array2)) print(result)

Output
[[1 2 3]
[4 5 6]]
Example 2
Below is the example which shows how a 1-D array can be stacked with a
2-D array, provided they are compatible in shape along the axis being
stacked −

import numpy as np
array1 = np.array([1, 2, 3])
array2 = np.array([[4, 5, 6], [7, 8, 9]])
result = np.vstack((array1, array2))
print(result)
Output
[[1 2 3]
[4 5 6]
[7 8 9]]
Splitting Arrays
Splitting arrays in NumPy splits arrays into smaller arrays along specified axes

Sr.N
Array & Description
o.
1 split Splits an array into multiple sub-arrays

2 hsplit Splits an array into multiple sub-arrays horizontally (column-


wise)
3 vsplit Splits an array into multiple sub-arrays vertically (row-wise)
The Numpy split() Function divides an array into multiple subarrays
along a specified axis. It can split the array into equal-sized subarrays if
given an integer or at specified indices if given a list.
This function is particularly useful for breaking down data into smaller
chunks for easier manipulation and analysis
numpy.split(ary, indices_or_sections, axis=0)
Parameters
Below are the parameters of the Numpy split() Function −
•ary(array_like): The input array to be split.
•indices_or_sections(int or 1-D array): If an integer(N), the array will
be divided into N equal sections. If an array, the values in the array
indicate where to split the array.
•axis(int, optional): The axis along which to split, default is 0 i.e. split
along rows.
Example 1
Following is the example of the shows Numpy split() Function which helps in splitting
an array of 9 elements into 3 equal sub-arrays −
import numpy as np # Create an array arr = np.arange(9)
print("Original array:")
print(arr)
# Split the array into 3 equal parts
result = np.split(arr, 3)
Output
print("\nSplit array into 3 equalparts:") Original array:
for i, sub_array in enumerate(result): [0 1 2 3 4 5 6 7 8]
print(f"Sub-array {i+1}:") Split array into 3 equal parts:
Sub-array 1:
print(sub_array) [0 1 2]
Sub-array 2:
[3 4 5]
Sub-array 3:
[6 7 8]
Example 2
Here in this example we show how to split a 2D array into 2 sub-arrays
along the columns i.e. axis=1 −

import numpy as np # Create a 2D array


arr = np.arange(16).reshape(4, 4)
print("Original 2D array:")
print(arr) # Split the 2D array into 2 sub-arrays along
columns
result = np.split(arr, 2, axis=1)
print("\nSplit 2D array into 2 sub-arrays along columns:")
for i, sub_array in enumerate(result):
print(f"Sub-array {i+1}:")
print(sub_array)
Original 2D array:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]

Split 2D array into 2 sub-arrays along columns:


Sub-array 1:
[[ 0 1]
[ 4 5]
[ 8 9]
[12 13]]
Sub-array 2:
[[ 2 3]
[ 6 7]
[10 11]
[14 15]]
The Numpy hsplit() Function is used to split an array into multiple sub-
arrays along its horizontal axis i.e. axis 1.
This function takes two main arguments one is the input array and the
number or array of indices where the splits should occur. It returns a list
of sub-arrays that are created by splitting the original array.
numpy.hsplit(ary, indices_or_sections)

Parameters
Following are the parameters of the Numpy hsplit() Function −
•ary: The input array to be split.
•indices_or_sections(int or 1-D array): This is either an integer
indicating the number of equal division sections to split the array into
along the second axis i.e. axis=1 or a list of indices where the array is
Example 1
Following is the example of Numpy hsplit() function which splits the
array into 2 sub-arrays along the columns −

import numpy as np
arr = np.arange(12).reshape(3, 4)
print("Original Array:")
print(arr) split_arrays =
np.hsplit(arr, 2) print("\nSplit
Arrays:")
for a in split_arrays:
print(a)
Original Array:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]

Split Arrays:
[[0 1]
[4 5]
[8 9]]
[[ 2 3]
[ 6 7]
[10 11]]
Example 2
Here in this example we show how numpy hsplit() function handles indices that
exceed array dimensions by creating empty arrays −

import numpy as np
arr = np.arange(10).reshape(2, 5)
print("Original Array:")
print(arr)
split_arrays = np.hsplit(arr, [2, 6]) # Using indices exceeding array size
print("\nSplit Arrays:")
for a in split_arrays:
print(a)
Original Array:
[[0 1 2 3 4]
[5 6 7 8 9]]

Split Arrays:
[[0 1]
[5 6]]
[[2 3 4]
[7 8 9]]
[]
Example 3
In this example hsplit() function divides the original array into two
equal-width sections horizontally. Each section is then printed to
show the result of the horizontal split −
import numpy as np # Create a 4x4 array with values from 0 to 15
a = np.arange(16).reshape(4, 4)
print('First array:')
print(a)
print('\n') # Split the array horizontally into 2 equal parts
b = np.hsplit(a, 2)
print('Horizontal splitting:')
for i, section in enumerate(b):
print('Section {}:'.format(i + 1))
print(section)
print('\n')
First array:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]

Horizontal splitting:
Section 1:
[[ 0 1]
[ 4 5]
[ 8 9]
[12 13]]

Section 2:
[[ 2 3]
[ 6 7]
[10 11]
[14 15]]
The Numpy vsplit() function is used to split an array into multiple sub-
arrays along the vertical axis (axis 0). It is used for dividing a 2D array
into smaller arrays row-wise. This function requires two arguments one is
the array to split and the other one is number of sections to create.
For example, if we have a 2D array with shape (6, 4) and use
np.vsplit(array, 3), it will return three sub-arrays, each with shape (2, 4).

numpy.vsplit(array, indices_or_sections)
Parameters
Following is the syntax of Numpy vsplit() function −
•ary(array_like): The input array to be split.
•indices_or_sections: This parameter can be an integer indicating the number of equally shaped
sub-arrays to create along the vertical axis or a 1-D array of sorted integers specifying the split
points.
Example 1
Following is the example of Numpy vsplit() function in which the
array arr is split vertically into 2 equally shaped sub-arrays −

import numpy as np # Create an array arr =


np.arange(16).reshape((4, 4))
# Split the array into 2 equal parts vertically
result = np.vsplit(arr, 2)
# Print the original array and the resulting sub-arrays
print("Original Array:")
print(arr)
print("\nAfter vsplitting into 2 parts:")
for sub_arr in result:
print(sub_arr)
Original Array:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]

After vsplitting into 2 parts:


[[0 1 2 3]
[4 5 6 7]]
[[ 8 9 10 11]
[12 13 14 15]]
Example 2
Below example shows how to use the hsplit() function handles indices that
exceed array dimensions by creating empty arrays −

import numpy as np # Create a 2D array with shape (4, 5)


arr = np.arange(20).reshape((4, 5)) # Split the array
into 2 parts vertically
result = np.vsplit(arr, 2) # Print the original array and
the resulting sub-arrays
print("Original Array:")
print(arr)
print("\nAfter vsplitting into 2 parts:")
for sub_arr in result:
print(sub_arr)
Original Array:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]

After vsplitting into 2 parts:


[[0 1 2 3 4]
[5 6 7 8 9]]
[[10 11 12 13 14]
[15 16 17 18 19]]
Indexing an NumPy Array
Indexing is used to extract individual elements from a one-dimensional
array.
It can also be used to extract rows, columns, or planes in a multi-
dimensional NumPy array .
Indexing Using Index arrays
Indexing can be done in NumPy by using an array as an index.
Numpy arrays can be indexed with other arrays or any other sequence
with the exception of tuples. The last element is indexed by -1 second last
by -2 and so on.
Example: Indexing using an index array
import numpy as np
# Create a sequence of integers from 10 to 1 with a step of -2
a = np.arange(10, 1, -2)
print("\n A sequential array with a negative step: \n",a)
# Indexes are specified inside the np.array method.
newarr = a[np.array([3, 1, 2 ])]
print("\n Elements at these indices are:\n",newarr)
Output :
A sequential array with a negative step:
[10 8 6 4 2]
Elements at these indices are:
[4 8 6]
Types of Indexing in NumPy Array
There are two types of indexing used in Python NumPy:
•Basic slicing and indexing
•Advanced indexing
• Purely integer indexing
• Boolean indexing
Basic Slicing and indexing
Basic slicing and indexing is used to access a specific element or range of
elements from a NumPy array.
Basic slicing and indexing only return the view of the array.
Consider the syntax x[obj] where “x” is the array and “obj” is the index.
The slice object is the index in the case of basic slicing.
Basic slicing occurs when obj is:
1.A slice object that is of the form start: stop: step
2.An integer
3.Or a tuple of slice objects and integers
All arrays generated by basic slicing are always ‘view’ of the original array.
Example: Basic Slicing in NumPy array

import numpy as np
# Arrange elements from 0 to 19
a = np.arrange(20)
print("\n Array is:\n ",a)
print("\n a[15]=",a[15])
# a[start:stop:step]
print("\n a[-8:17:1] = ",a[-8:17:1])
print("\n a[10:] = ",a[10:])

Array is:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
a[15]= 15
a[-8:17:1] = [12 13 14 15 16]
a[10:] = [10 11 12 13 14 15 16 17 18 19]
Advanced indexing
NumPy Advanced indexing returns a copy of data rather than a view
of it. Advanced indexing is of two types integer and Boolean.
Advanced indexing in the NumPy array allows you to access and
manipulate complex patterns of the data.
Advanced indexing is triggered when obj is :
•an ndarray of type integer or Boolean
•or a tuple with at least one sequence object
•is a non tuple sequence object
Types of Advanced Indexing
There are two types of Advanced Indexing in NumPy array indexing:
•Purely integer indexing
•Boolean integer indexing
Purely integer array indexing
Purely integer array indexing allows us to access elements from an
ndarray (N-dimensional array) using integers.
When integers are used for indexing. Each element of the first
dimension is paired with the element of the second dimension. So the
index of the elements in this case are (0,0),(1,0),(2,1) and the
corresponding elements are selected.
Example: Using purely integer array indexing

#Python program showing advanced indexing import numpy as np


a = np.array([[1 ,2 ],[3 ,4 ],[5 ,6 ]])
print(a[[0 ,1 ,2 ],[0 ,0 ,1]])

[1 3 6]
Boolean Indexing
This indexing has some boolean expressions as the index.
Those elements are returned which satisfy that Boolean expression. It is
used for filtering the desired element values.

Example 1: Using boolean indexing on NumPy array to find


numbers greater than 50

#You may wish to select numbers greater than 50


import numpy as np a = np.array([10, 40, 80, 50, 100])
print(a[a>50])

[80 100]
Example 2: Using boolean indexing on NumPy array to find numbers
whose sum row is 10

# You may wish to select those elements whose


# sum of row is a multiple of 10.
import numpy as np
b = np.array([[5, 5],[4, 5],[16, 4]])
sumrow = b.sum(-1)
print(b[sumrow%10==0])

array([[ 5, 5], [16, 4]])


Python Iterators
Iterators are methods that iterate collections like lists, tuples, etc. Using an
iterator method, we can loop through an object and return its elements.
Python iterator object must implement two special
methods, __iter__() and __next__(),
collectively called the iterator protocol.
An iterator in Python is an object that is used to iterate over iterable
objects like lists, tuples, dicts, and sets. The Python iterators object is
initialized using the iter() method. It uses the next() method for iteration.
1.__iter__(): The iter() method is called for the initialization of an iterator.
This returns an iterator object
2.__next__(): The next method returns the next value for the iterable.
When we use a for loop to traverse any iterable object, internally it uses
the iter() method to get an iterator object, which further uses the next()
method to iterate over. This method raises a StopIteration to signal the end
of the iteration.
Python iter() Example

string = "GFG"
ch_iterator = iter(string)
print(next(ch_iterator))
print(next(ch_iterator))
print(next(ch_iterator))

G
F
G
Numpy | Iterating
Over Array
NumPy package contains an iterator object numpy.nditer. It is an efficient
multidimensional iterator object using which it is possible to iterate over
an array. Each element of an array is visited using Python’s standard
Iterator interface.
# Python program for
# iterating over array
import numpy as geek
# creating an array using arrange method
a = geek.arange(12)
# shape array with 3 rows and 4 columns
a = a.reshape(3,4)
print('Original array is:')
print(a)
print()
print('Modified array is:')
# iterating an array
for x in geek.nditer(a):
print(x)
Original array is:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Modified array is:
0
1
2
3
4
5
6
7
8
9
10
11
Controlling Iteration Order:
There are times when it is important to visit the elements of an array in a
specific order, irrespective of the layout of the elements in memory. The
nditer object provides an order parameter to control this aspect of
iteration.
The default, having the behavior described above, is order=’K’ to keep
the existing order. This can be overridden with order=’C’ for C order and
order=’F’ for Fortran order.
# Python program for
# iterating over array
# using particular order
import numpy as geek
# creating an array using arrange method
a = geek.arange(12)
# shape array with 3 rows and 4 columns
a = a.reshape(3,4)
print('Original array is:')
print(a)
print()
print('Modified array in C-style order:')
# iterating an array in a given # order
for x in geek.nditer(a, order = 'C'):
print(x)
Original array is:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Modified array is:
0
1
2
3
4
5
6
7
8
9
10
11
# Python program for
# iterating over array
# using particular order
import numpy as geek
# creating an array using arrange method
a = geek.arange(0,60,5)
# shape array with 3 rows and 4 columns
a = a.reshape(3,4)
print('Original array is:')
print(a)
print()
print('Modified array in F-style order:')
# iterating an array in a given order
for x in geek.nditer(a, order = 'F’):
print(x)
Original array is:
[[ 0 5 10 15]
[20 25 30 35]
[40 45 50 55]]
Modified array in F-style order:
0
20
40
5
25
45
10
30
50
15
35
55
Modifying Array Values:
The nditer object has another optional parameter called op_flags. Its
default value is read-only, but can be set to read-write or write-only mode.
This will enable modifying array elements using this iterator.
# Python program for
# modifying array values
import numpy as geek
# creating an array using arrange method
a = geek.arange(12)
# shape array with 3 rows and 4 columns
a = a.reshape(3,4)
print('Original array is:')
print(a)
# modifying array values
for x in geek.nditer(a, op_flags = ['readwrite']):
x[...] = 5*x
print('Modified array is:')
Original array is:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Modified array is:
[[ 0 5 10 15]
[20 25 30 35]
[40 45 50 55]]
Broadcasting Iteration:
If two arrays are broadcastable, a combined nditer object is able to
iterate upon them concurrently. Assuming that an array a has dimension
3X4, and there is another array b of dimension 1X4, the iterator of
following type is used (array b is broadcast to size of a).
# Python program for
# iterating array
import numpy as geek
# creating an array using arrange method
a = geek.arange(12)
# shape array with 3 rows and 4 columns
a = a.reshape(3,4)
print('First array is:')
print(a)
print()
# Creating second array using array method
print('Second array is:')
b = geek.array([5, 6, 7, 8], dtype = int)
print(b)
print()
print('Modified array is:')
for x,y in geek.nditer([a,b]):
print("%d:%d" % (x,y))
First array is:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Second array is:
[5 6 7 8]
Modified array is:
0:5
1:6
2:7
3:8
4:5
5:6
6:7
7:8
8:5
9:6
10:7
Boolean Array in NumPy
import numpy as np
arr = np.array([1, 0, 1, 0, 0, 1, 0])
print(f'Original Array: {arr}')
bool_arr = np.array(arr, dtype='bool')
print(f'Boolean Array: {bool_arr}')

Original Array:
[1 0 1 0 0 1 0]
Boolean Array:
[ True False True False False True False]
import numpy as np
arr = np.array([5, None, 1, 25, -10, 0, 'A'])
print(f'Original Array: {arr}')
bool_arr = np.array(arr, dtype='bool')
print(f'Boolean Array: {bool_arr}')

Original Array:
[5 None 1 25 -10 0 'A’]
Boolean Array: [ True False True True True False True]
NumPy where() Multiple Conditions( Conditional Array )
When we pass the NumPy array to the numpy.where() it will return the indices of NumPy
array elements

# Import numpy import numpy


as np
arr = np.array([5, 10, 15, 20,
25])
print("Given array:", arr)
# Get the indices of array
elements
arr1=np.where(arr)
print("Get indices of given
array:", arr1)
NumPy where() Multiple Conditions With the & Operator
To select the NumPy array elements from the existing array based on multiple conditions use
the & operator along with the where() function. You can specify multiple conditions inside
the where() function by enclosing each condition inside a pair of parenthesis and using
an & operator

import numpy as np # Create a numpy array


arr = np.array([5, 10, 15, 20, 25])
# Use numpy.where() multiple conditions with the & operator
arr2 = arr[np.where((arr >5) & (arr <25))]
print("Get selected array elements:", arr2)
Use where() Multiple Conditions With the | Operator

You can use the np.where() function with multiple conditions to modify the existing
array based on those conditions.
In the below example, you can use the | (bitwise OR) operator to filter elements from a
NumPy array.
import numpy as np
# Create a numpy array
arr = np.array([5, 10, 15, 20, 25])
# Multiple conditions using | operator #
Use numpy.where() function
arr2 = arr[np.where((arr >5) | (arr % 2 == 0))]
print("Get selected array elements:\n", arr2)
# Output:
# Get selected array elements: # [10 15 20 25]
Use where() Multiple Conditions With the logical_and()

numpy.logical_and() function is used to calculate the element-wise truth value


of AND gate in Python. Using this function inside the where() function to specify multiple
conditions and get the selected elements from an existing array.
In this example, np.logical_and(arr > 5, arr < 25) creates a boolean array with
True where both conditions are satisfied and False otherwise. np.where() then finds the
indices where the conditions are True, and finally, these indices are used to extract the
corresponding elements from the original array.
import numpy as np
# Create a numpy array
arr = np.array([5, 10, 15, 20, 25])
# Use numpy.where() multiple conditions
# Using numpy.logical_and() function
arr2 = arr[np.where(np.logical_and(arr >5, arr <25))]
print("Get selected array element:", arr2)
# Output:
# Get selected array element: [10 15 20]
Use where() Multiple Conditions With the logical_or()

import numpy as np
# Create a numpy array
arr = np.array([5, 10, 15, 20, 25])
# Use numpy.where() multiple conditions with the .logical_or()
arr2 = arr[np.where(np.logical_or(arr >5, arr % 2 == 0))]
print("Get selected array element:", arr2)
# Output:
# Get selected array element: [ 10 15 20 25]
Numpy | Linear Algebra
The Linear Algebra module of NumPy offers various methods to apply
linear algebra on any numpy array.
One can find:
•rank, determinant, trace, etc. of an array.
•eigen values of matrices
•matrix and vector products (dot, inner, outer,etc. product), matrix
exponentiation
•solve linear or tensor equations and much more!
# Importing numpy as np
import numpy as np
A = np.array([[6, 1, 1],
[4, -2, 5],
[2, 8, 7]])
# Rank of a matrix
print("Rank of A:", np.linalg.matrix_rank(A))
# Trace of matrix A
print("\nTrace of A:", np.trace(A))
# Determinant of a matrix
print("\nDeterminant of A:", np.linalg.det(A))
# Inverse of matrix A
print("\nInverse of A:\n", np.linalg.inv(A))
print("\nMatrix A raised to power 3:\n",np.linalg.matrix_power(A, 3))
Rank of A: 3
Trace of A: 11
Determinant of A: -306.0
Inverse of A: [[ 0.17647059 -0.00326797 -0.02287582]
[ 0.05882353 -0.13071895 0.08496732]
[-0.11764706 0.1503268 0.05228758]]
Matrix A r...
NumPy Linear Algebra
Numpy provides the following functions to perform the different
algebraic calculations on the input data.
SN Function Definition

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

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

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

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

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

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

7 inv() It is used to calculate the multiplicative inverse of the matrix.


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
import numpy as np
a = np.array([[100,200],[23,12]])
b = np.array([[10,20],[12,21]])
dot = np.dot(a,b)
print(dot)
[[3400 6200] [ 374 712]]

The dot product is calculated as: [100 * 10 + 200 * 12, 100 * 20 + 200 * 21] [23*10+12*12,
23*20 + 12*21]
numpy.vdot() function
This function is used to calculate the dot product of two vectors. It can be defined as the
sum of the product of corresponding elements of multi-dimensional arrays.

import numpy as np
a = np.array([[100,200],[23,12]])
b = np.array([[10,20],[12,21]])
vdot = np.vdot(a,b)
print(vdot)

5528
np.vdot(a,b) = 100 *10 + 200 * 20 + 23 * 12 + 12 * 21 = 5528
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.
import numpy as np
a = np.array([1,2,3,4,5,6])
b = np.array([23,23,12,2,1,2])
nner = np.inner(a,b)
print(inner)

130
NumPy outer() Function
The outer() function in NumPy computes the outer product of two arrays,
which is the product of all possible pairs of their entries.

import numpy as np
array1 = np.array([1, 3, 5])
array2 = np.array([2, 4, 6])
# outer() to perform outer multiplication
result = np.outer(array1, array2)
print(result)
[[ 2 4 6]
[ 6 12 18]
[10 20 30]]
NumPy solve() Function
In NumPy, we use the solve() function to solve a system of linear
equations.
For a given matrix A and a vector b, solve(A, b) finds the solution
vector x that satisfies the equation Ax = b.
import numpy as np
# define the coefficient matrix A
A = np.array([[2, 4],
[6, 8]])
# define the constant vector b
b = np.array([5, 6])
# solve the system of linear equations Ax = b
x = np.linalg.solve(A, b)
print(x)
# Output: [-2. 2.25]

solution to the system of linear equations 2x + 4y = 5 and 6x + 8y = 6.


Reverse the order of the items in the array

from array import * array_num = array('i', [1, 3, 5, 3, 7, 1, 9,


3])
print("Original array: "+str(array_num))
array_num.reverse()
print("Reverse the order of the items:")
print(str(array_num))

Original array: array('i', [1, 3, 5, 3, 7, 1, 9, 3])


Reverse the order of the items: array('i', [3, 9, 1, 7, 3, 5, 3,
1])
Get the number of occurrences of a specified element in
an array
from array import *
array_num = array('i', [1, 3, 5, 3, 7, 9, 3])
print("Original array: "+str(array_num))
print("Number of occurrences of the number 3 in the said array: "+str(array_num.count(3)))

Original array: array('i', [1, 3, 5, 3, 7, 9, 3])


Number of occurrences of the number 3 in the said
array: 3
Reading and Writing to text files in Python

Python provides built-in functions for creating, writing, and reading files.
Two types of files can be handled in Python, normal text files and binary
files (written in binary language, 0s, and 1s).
•Text files: In this type of file, Each line of text is terminated with a
special character called EOL (End of Line), which is the new line character
(‘\n’) in Python by default.
•Binary files: In this type of file, there is no terminator for a line, and the
data is stored after converting it into machine-understandable binary
language.

You might also like