Posts

Showing posts from 2026

Array operations in NumPy – Aggregate and Advanced Operations:

               Arrays in numpy has variety of operations like element-wise arithmetic, Scalar Operations, Aggregate and advanced functions. The basic operations are already discussed. Now,we discuss about the aggregate and advanced functions. Python Numpy Code for Aggregate and Advanced Operations:               This code starts from importing Numpy library. First,create two arrays with elements. Next,Aggregate functions like sum of all elements,Mean value,max and min values are calculated with built-in functions. Advanced functions like Dot product,square root and exponential are also calculated with built-in function. Code:   import numpy as np # Let us Create two arrays s_arr1 = np.array([1, 3, 5, 7]) s_arr2 = np.array([2, 4, 6, 8]) #Aggregate functions print("Sum:", np.sum(s_arr1))             ...

Scalar Multiplication in Numpy

               Here, we use Scalar multiplications in different ways. Let us try three methods listed as follows.. ·        1D array scalar multiplication ·        2D array scalar multiplication ·        Different scalars for each column The sample code is given below. 1D array scalar multiplication:   This code multiplies the array by 3. First, it creates an array of elements. Each element is multiplied by 3. The result is displayed. Code: import numpy as np1 # Create an array with elements s_arr = np1.array([1, 3, 5, 7, 9, 11, 13, 15]) # Scalar multiplication by 3 result = s_arr * 3 print("Original array:", s_arr)    print("Multiplied by 3:", result) Output: Original array: [ 1   3   5   7   9 11 13 15] Multiplied by 3: [ 3   9 15 21 27 33 39 45] 2D array scalar multiplication: ...

How to implement element-wise addition,subtraction and multiplication in Numpy?

              Array is a collection of similar data elements. When you implement the arithmetic operations, you have to do each element. Let us implement this as follows. Element-wise Arithmetic Operations in Numpy:               It starts from importing numpy library. First, two arrays are included as input. Element wise operations are performed and result is printed. Code: import numpy as np1 # Two arrays as input s_arr1 = np1.array([11, 22, 33, 44]) s_arr2 = np1.array([5, 10, 15, 20]) # Arithmetic operations on element wise print("Element wise Arithmetic Operations:") print("Addition:", s_arr1 + s_arr2)         print("Subtraction:", s_arr2 - s_arr1)      print("Multiplication:", s_arr1 * s_arr2)   Output: Element wise Arithmetic Operations: Addition: [16 32 48 64] Subtraction: [ -6 -12 -18 -24] ...

Indexing and slicing arrays in python numpy

               Indexing is the process of retrieving specific elements, whereas slicing extracts subarrays in a range. Both methods support negative indices and returns the original array elements. Mainly, these two methods make the user to access, extract the elements and manipulates the array in efficient manner. Let us discuss the methods with sample code as follows… Indexing in Numpy:               It supports three methods as follows. ·        Single element indexing ·        Multi-dimensional indexing ·        Index arrays The sample code is given below.. Single element indexing:               It follows list concept in python. Code: import numpy as np1 s_arr = np1.arange(10)    # [0,1,2,3,4,...

How to practice with .dtype and .shape in Numpy?

       Numpy has attributes for arrays. These attributes describes the structure and the content. These are given below… ·        .dtype ·        .shape .dtype:               It means ‘data type’. It gives the information about the values to be stored in the array. eg. Integers,floats,strings. .shape:               It provides the dimensions of the array. It may be of single dimensional, two dimensional or three dimensional. Let us create python program to implement using Numpy. Sample Python Numpy code for .dtype: # Example 1: Integer array Import numpy as np s_int = np.array([11, 22, 33, 44]) print("Array Elements:", s_int) print("Data type of the Array is:", s_int.dtype) Output: Array Elements: [11 22 33 44] Data type of the Array is: int64 #...

Numpy- How to import and install?

              ‘Numpy’- a python library which holds many built-in functions specially designed for scientific computing. It is efficient for multidimensional arrays. It supports data science, machine learning. It provides the following features. ‘ndarray’- it supports N-dimensional array. Automatic alignment can be done. Operations are vectorized. It supports many libraries. High performance is achieved. Let us follow the steps to import and install the Numpy in your system. First, open the command prompt or terminal In windows: search tab, type Command Prompt. Other Os like macOS/Linux: open the Terminal. Next, run the pip command with Numpy keyword. C:\Users>python -m pip install numpy It successfully install your Numpy. Once, it was successfully installed, check it with following code. C:\Users>pip list Package             Version ------------------ ------...

Python Program to compute the determinant of a matrix?

               Let us compute the determinant of a matrix using the Numpy Library. How to find determinant of a matrix in mathematical way?               It is a scalar value that deals with a square matrix. It is denoted by det(A) or |A|. If it is a 2×2 matrix, it follows this formula. For A=[abcd], the determinant is |A|=ad−bc. If it is a 3x3 matrix, it uses /laplace expansion or cofactor method. If you have nxn matrix, it uses Leibniz formaula,Laplace expansion or Gaussian elimination. Let us implement in three ways. 1.       Normal method. 2.       Using Numpy 3.       Using Laplace 1.Normal method.               This method uses the simple code implementation. Code: # 2x2 determinant without NumPy def det_2x2(s_ma...

How to find Eigen value and Eigen vector using Python

       These are the concepts available in Linear algebra. It has the following definitions. Eigenvalue( λ ): It is a scalar value.It shows about the eigen vector stretch and compress in terms of linear transformation. Eigenvector(v): It is a vector value.It is a non-zero vector which changes the scale alone. The formula for square matrix A is given below. Av=λv Where A represents matrix. ‘v’ denotes eigenvector. ‘λ’ is for eigenvalue. Let us implement the eigen value and eigen vector in python. This program imports numpy package with its object np. A square matrix is created with elements. Eigenvalues and eigenvectors variables are declared. There is a function ‘linalg.eig(matrix)’ which generate the eigenvalues and eigenvectors. Python Program: import numpy as np # Declare a square matrix A = np.array([[5, 3, 2],               [1,-1, 4],      ...

How to solve a system of linear equations using Numpy?

              System of linear equations have a set of equations with same variable. It has a solution of values which suits all the equations. It can be done by input validation, error handling. Let us create a python program to solve this. Code: import numpy as np def solveIt_linear_system():     try:         # Input statement         n = int(input("Enter the number of equations/variables: "))         if n <= 0:             print("Number of equations must be positive.")             return         # Read the coefficient matrix         print(f"Enter the {n}x{n} coefficient matrix (row by row):")      ...

Aggregations on matrix in Python

               Aggregations are the data transformation techniques which produces scalar values from arrays. Let us implement this two ways 1.       Using python code 2.       Using Numpy The code is given below… 1.Using python code:               This method creates a matrix.It calculates the row wise sum,column wise sum and overall sum. It also finds the maximum value in row wise and column wise. Finally,it displays the values. Code: s_matrix = [     [2, 2, 1],     [6, 5, 4],     [3, 8, 9] ] # Let us find Row-wise sum row_sums = [sum(row) for row in s_matrix] # Let us find Column-wise sum col_sums = [sum(s_matrix[r][c] for r in range(len(s_matrix))) for c in range(len(s_matrix[0]))] # Sum of all the elements total_sum = sum(sum(row) for row in s_ma...

Advance functions for Random number generation in Python

               Random Number generation can be categoried into three categories. Part1 describes the basic type. Part2 deals with the probability distributions. Part3 covers the advanced Random number Generation. To read the part1,part2,just follow the link. https://rajeeva84.blogspot.com/2026/08/random-number-generation-in-python.html https://rajeeva84.blogspot.com/2026/08/random-number-generation-in-python_02076504341.html Advanced methods are given below… ·        Random State / Seed ·        Cryptographically Secure Randoms 1.Random State/Seed:               It uses ‘seed()’ method. This helps to initialize the generator. As a default value,it seeds the current system time. First method uses randint() function to print random value. Second method uses seed() method. Python code: import random # Wi...

Random number Generation in Python part2(Probability Distributions)

               Part 1 blog post explained the basic random number generations. This blog post includes the methods in Probability distributions. The methods are listed below… ·        Normal Distribution ·        Binomial distribution ·        Poisson distribution ·        Exponential distribution 1.Normal Distribution               It is the most widely used distribution. It is symmetric with mean, standard deviation values. Code: #create an object for numpy import numpy as np1 print("Normal distribution values are:") #generate normal distribution with mean 1 std as 2 with 4 elements print(np1.random.normal(1,2,4))   Output: Normal distribution values are: [ 1.40837209  2.3509239  -0.15261431 -0.09280015] 2.Binomial ...

Random number Generation in Python

               It can be implemented by many methods based on user requirements.Based on the fucntions,the list is given below. ‘randint()’ ‘random()’ or ‘uniform()’ ‘choice()’ ‘sample()’ ‘shuffle()’ ‘seed()’ ‘secrets.randbelow()’ ‘rand()’ Various types of Distrbutions 1. ‘randint()’:               This function is a built-in function of random package. It reads the number limit to generate random values. Code: # This code imports random package import random print("The random value is:") #prints the random integer value in the range 1 to 100. print(random.randint(1, 100))   Output: The random value is: 11 2.‘random()’ or ‘uniform()’:               This generates random float number. ‘random()’ gives a single float number. ‘uniform()’ gives you the float number within the r...

Matrix Multiplication in python

              Matrix multiplication can be done by multiplying each row with each column. It can be done when the rows of first matrix and column of second matrix should be equal. Let us implement the matrix multiplication as follows. This can be done by two ways. Using Numpy Using Lists Using Numpy:               This program uses Numpy functions dot(),@ to generate matrix multiplication. Code: import numpy as np1 # Define two matrices X = np1.array([[2, 3],               [4, 1]]) Y = np1.array([[8, 6],               [7, 5]]) # Matrix multiplication Z = np1.dot(X, Y)   # Method 1 A = X @ Y          # Method 2 (Python 3.5+) print("Matrix Multiplication Using np.dot:\n", Z) print("Matrix Multiplication Using @ operator:\n", A) Output: Matrix Multiplica...

Transpose matrix implementation in python

              Transpose means changing column into rows and rows into columns. It can be implemented in python with or without Numpy. There are three methods to implement as follows. ·        Using Numpy ·        Using Zip ·        Manual Loops Using Numpy:               Numpy is predefined. It has many built-in functions. Pyhon code: import numpy as np1 # Step 1: create a 4X4 matrix X = np1.array([[1, 2, 3, 6],               [4, 5, 6, 10],               [7, 8, 9, 2],               [3, 6, 4, 8]]) # Step 2: Transpose the matrix X X_T = X.T print("The Original Matrix:\n", X) print("Here is the Transposed Matrix:\n", X_T) Output: The Original Matrix:  [[ 1...

Implementation of Identity Matrix in Python

             Identify Matrix has the rows and columns in equal manner. It has ones on the diagonal and zeros in other places. This can be done two different ways as follows… ·        Using Numpy ·        Using Plain Python Code 1.Using Numpy:               This method uses the ‘Numpy’ to create object and calling built-in functions. Implementation: ·        It uses Numpy built-in file and creates the object. It calls the ‘identity()’ function to build the identity matrix. ·        Finally,prints the identity matrix. Code: #Using Numpy import numpy as np1 # Create a 4x4 identity matrix I = np1.identity(4) print("Here is the Identity Matrix using Numpy:") print(I) Output: Here is the Identity Matrix using Numpy: [[1. 0. 0. 0.]  [0...