__author__ = "Narendra Boyina"
# -----------------------------------------------------------------------------
# Copyright (c) 2025 BR Technologies PVT LTD
# -----------------------------------------------------------------------------
"""Concepts to be Covered on numpy concept.
7. Initialization of arrays
np.arange(), np.zeros(), np.ones() --> 2 dimensions & 3 dimensions
np.full(), np.eye()
8. Array Manipulations
np.resize(), np.reshape(),ravel() vs flatten(), np.matmul(), np.transpose(),
9. Functions
a. Aggregate Functions
b. Broadcast
c. Exponential and Logarithmic Functions
10. Arrays Splitting and Joining
a. np.split() vs np.array_split()
b. np.hstack() Vs np.vstack()
11. Array Adding and Removing Elements
a. np.append(), np.insert(). np.delete()
12. Pseudo-random Number Generation
a. np.random.randint()
b. np.random.normal()
c. np.random.rand()
"""
import numpy as np
""" # np.arange(): Used to create an array with regularly spaced values within a specified range """
# Create an array from 0 to 14
range_of_elements = np.arange(15)
# print(range_of_elements) # Output: [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
range_of_element = np.arange(0,100,20, dtype = int)
# print(range_of_element) # print the 0 to 100 values with difference of 20.
range_of_element = np.arange(0,100,20, dtype = float)
# print(range_of_element) # print the 0 to 100 values with difference of 20.
""" # np.zeros() & np.ones()
--> np.zeros creates an array filled with zeros & np.ones creates an array filled with ones.
--> It takes the shape of the desired array as input and returns an array of that shape filled with zeros
--> by default it will fill with float values """
# Create a 2x3 array filled with zeros
zeros_array = np.zeros([2, 3])
# print(zeros_array)
""" Output: 2x3 array--> 2 rows and 3 colums
[[0. 0. 0.]
[0. 0. 0.]]
"""
# Create a 2x3 array filled with ones
ones_array = np.ones([2, 3])
# print(ones_array)
# Create a 3D array filled with zeros
arr_3d = np.zeros([2, 3, 4]) # 2-Blocks, 3-rows, 4-colums
# print(arr_3d)
# Create a 3D array filled with ones
arr_3d = np.ones([2, 3, 4]) # 2-Blocks, 3-rows, 4-colums
# print(arr_3d)
# Print the number of dimensions
# print("Number of dimensions:", arr_3d.ndim) # Output: 3
"""# np.full()
--> np.full creates an array filled with a specified constant value.
--> It takes the shape of the desired array and the constant value as input, and returns an array of that shape filled with the specified value.
Syntax: numpy.full(shape, fill_value, dtype=None)"""
# Create a 2x2 array filled with 5
full_array = np.full((2, 2), 5) #(2,2) dimension , dimension is filled with 2.1
# print(full_array)
""" # np.eye():
--> used to create a 2-D array with "ones on the diagonal" and zeros elsewhere.
--> useful for creating "identity matrices" or matrices with specific diagonal patterns."""
# Create a 3x3 identity matrix --> is a square matrix with 1s on the diagonal and 0s elsewhere.
matrix = np.eye(3)
# print(matrix)
""" ######## Array Manipulations ########"""
""" # np.resize() : changes the shape and size of an array in-place."""
# array = np.arange(10) # One_d_array creation
# print("Created new array:",array) # [0 1 2 3 4 5 6 7 8 9]
# array.resize(2,3)
# print("Resized with 2X3 :\n", array )
# array = np.arange(10) # One_d_array creation
# print("Created new array:",array) # [0 1 2 3 4 5 6 7 8 9]
# array.resize(2,5)
# print("Resized with 2X5 :\n", array )
# array = np.arange(10) # One_d_array creation
# print("Created new array:",array) # [0 1 2 3 4 5 6 7 8 9]
# array.resize(2,7)
# print("Resized with 2X7 :\n", array )
""" # np.reshape():
--> Reshaping an array means changing the shape of the array without changing its data.
--> It's useful for converting arrays between different dimensions or rearranging their layout """
# Create a one-dimensional array of 12 elements
Created_array = np.arange(12)
# print("Original array: ", Created_array)
# Reshape it to a 3x4 two-dimensional array
Reshaped_array = Created_array.reshape(3,4)
# print("Reshaped array:\n", Reshaped_array)
""" Difference between ravel() and flatten() in numpy
Both ravel() and flatten() in NumPy are used to convert a multi-dimensional array into a 1D array,
but there's a key difference in how they handle memory ---> like shallow copy(ravel) & deepcopy(flatten)
Memory usage
--> of ravel is More memory-efficient
--> of flatten is Uses more memory (new object)"""
""" #np.ravel()
--> The ravel() method convert Multi-dimensional array to an one-dimensional array.
--> it uses same memory location of the original array like shallow copy"""
raveled_array = Reshaped_array.ravel() # Flatten the 3x4 array to a one-dimensional array
# print("raveled array:", raveled_array)
""" # np.flatten()
--> Similar to ravel(), flatten() convert Multi-dimensional array to an one-dimensional array.
--> It creates a separate memory location for the new array,
--> Due to different memory location, if we do any modification, it will not affecting the original array """
# print("Reshaped array:\n", Reshaped_array)
# flatten_array = Reshaped_array.flatten()
# print("Flattened array:", flatten_array)
""" Example to show the Difference between ravel and flatten arrays """
"""Below we are going to explain ravel() related to memory --> shallow copy"""
# Creating a 2D array
created_2d_array = np.array([[1, 2], [3, 4]])
# print("created_2d_array:\n",created_2d_array)
raveled_array = created_2d_array.ravel() # converted to 1-D array using ravel()
# print("raveled_array : ", raveled_array)
raveled_array[0] = 100 # Modifying the raveled array
# print("Priniting Original array after modifying raveled array: \n", created_2d_array) # if you observe original array modified
"""Below we are going to explain flatten() related to memory --> Deep copy"""
# Creating a 2D array
created_2d_array = np.array([[1, 2], [3, 4]])
# print("created_2d_array:\n",created_2d_array)
flatten_array = created_2d_array.flatten() # converted to 1-D array using ravel()
# print("flatten_array : ", flatten_array)
flatten_array[0] = 150 # Modifying the flatten_array
# print("Priniting Original array after modifying flatten array: \n", created_2d_array) # if you observe original array will not be modified
""" # Matrix Multiplication (np.matmul()):
--> Matrix multiplication is a fundamental operation in linear algebra, where you multiply two matrices to obtain a new matrix.
--> In NumPy, you can perform matrix multiplication using the np.matmul() function. """
# Define matrices
matrix_mul_a = np.array([[1, 2], [3, 4]])
matrix_mul_b = np.array([[5, 6], [7, 8]])
# Matrix multiplication using np.matmul()
result = np.matmul(matrix_mul_a, matrix_mul_b)
# print("Matrix Multiplication:\n",result)
""" # Matrix Transpose (np.transpose()):
--> "Transposing a matrix" means flipping its rows with its columns.
--> In NumPy, you can obtain the transpose of a matrix using the np.transpose() function
--> In NumPy, you can transpose an array using the T attribute """
matrix_trans = np.array([[1,2,3],
[4,5,6]])
transposed_matrix = np.transpose(matrix_trans)
# print(transposed_matrix)
# Create a 2D array
arr_2d = np.array([[1, 2, 3],
[4, 5, 6]])
# Transpose the array
transposed_arr = arr_2d.T
# print("Transposed array: \n ", transposed_arr)
"""Aggregate Functions:
--> Aggregate functions in NumPy are functions that operate on arrays and return a single value, summarizing the data in some way.
--> Common aggregate functions include np.sum(), np.max(), np.min(), np.mean(), etc. """
matrix = np.array([[1, 2, 3],
[4, 5, 6]])
#print("Sum of all elements:", np.sum(matrix)) # Output: 21
#print("Maximum element:", np.max(matrix)) # Output: 6
#print("Minimum element:", np.min(matrix)) # Output: 1
#print("Mean of all elements(sum/total):", np.mean(matrix)) # Output: 3.5
""" Exponential and Logarithmic Functions """
math_data = np.array([1,2,3,4])
# Exponential
result_exp = np.exp(math_data)
# print("exponential :", result_exp)
# Natural logarithm
result_log = np.log(math_data)
# print("Logarithm", result_log)
""" Broadcasting:
--> NumPy automatically broadcasts arrays to perform element-wise operations
--> Universal functions also support broadcasting, which means they can operate on arrays of different shapes """
broad_arr =np.array([[1,3,2], [4,5,6]])
# Element-wise addition with scalar
result_broad = broad_arr + 2
# print("Broadcasting with Scalar:",result_broad)
"""##### Arrays Splitting and Joining #####"""
"""
--> Splitting allows you to divide large arrays into smaller arrays.
--> This can be useful for parallel processing tasks or during situations
where subsets of data need to be analyzed separately """
""" ###### np.split() vs np.array_split() ###### """
""" np.split()
--> Strict splitting: Only works if the array can be divided exactly into equal parts.
--> Raises an error if the split does not divide the array evenly
--> Syntax: np.split(array, indices_or_sections, axis=0) """
creating_1D_array = np.arange(9)
# print("Orginal aray:", creating_1D_array)
# splited_array = np.split(creating_1D_array,3) # Split the array into 3 equal parts
# print("splited_array:", splited_array)
#splited_array = np.split(creating_1D_array,4) # ValueError: array split does not result in an equal division
# print("splited_array:", splited_array)
"""np.array_split()
--> Flexible splitting: Allows unequal splits.
--> Will divide the array as evenly as possible and does not raise an error if the array can't be divided equally.
--> Syntax: np.array_split(array, indices_or_sections, axis=0) """
# Split the array into 4 parts, which will not be equal
# array_split = np.array_split(creating_1D_array, 4)
# print("Array split into unequal parts:", array_split)
""" #### np.hstack() Vs np.vstack() #### """
"""np.hstack() — Horizontal Stack
--> Joins arrays along columns (axis=1 for 2D arrays).
--> Think: side-by-side stacking.
--> Syntax: np.hstack((array1, array2, ...)) """
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
c = np.hstack((a, b))
# print(c)
# Output:
# [[1 2 5 6]
# [3 4 7 8]]
"""np.vstack() — Vertical Stack
--> Joins arrays along rows (axis=0 for 2D arrays).
--> Think: top-to-bottom stacking.
--> Syntax: np.vstack((array1, array2, ...)) """
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
c = np.vstack((a, b))
# print(c)
# Output:
# [[1 2]
# [3 4]
# [5 6]
# [7 8]]
####### Array Adding and Removing Elements #########
""" np.append: Adds elements to the end of an array """
array = np.array([101, 102, 103])
appended_aaray =np.append(array, [104, 105])
# print("Appended array: ", appended_aaray)
""" np.insert: Inserts elements at a specific position in the array """
array_after_inserted = np.insert(appended_aaray, 1, [2, 3, 4,])
# print("Array with inserted elements:", array_after_inserted)
""" np.delete: Removes elements at a specific position from the array """
# Create a one-dimensional array
creating_1D_array = np.arange(5,15)
# print(creating_1D_array)
# Delete the element at index 2
result = np.delete(creating_1D_array, 2)
# print("Array after deleting element at index 2:", result)
creating_1D_array = np.arange(5,15)
# print(creating_1D_array)
# Delete multiple elements
# result = np.delete(creating_1D_array, [0, 3]) # removes only particular indices
# print("Array after deleting elements at indices 0 and 3:", result)
# Create a two-dimensional array
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Delete the second row
result = np.delete(array_2d, 1, axis=0)
# print("Array after deleting second row:\n", result)
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Delete the third column
result = np.delete(array_2d, 2, axis=1) # deleted based on axis
# print("Array after deleting third column:\n", result)
""" Pseudo-random Number Generation:
--> NumPy provides various functions for generating pseudo-random numbers.
--> These functions are located in the numpy.random module.
--> You can generate random numbers from different distributions, such as uniform, normal, binomial, etc. """
""" # np.random.randint(): Generates required number of random integers between given range of values (1D / 2D arrays)"""
# Pseudo-random Number Generation in 1D Array: # Generate 5 random integers between 1 and 10
random_integers = np.random.randint(1, 10, size=5) # generates 1D array with 5 random values
# print("Random integers (1D):", random_integers)
# Generate a 2D array of shape (3, 4) with random integers between 1 and 10
random_integers_2d = np.random.randint(1, 10, size=(3, 4))
# print("Random integers (2D):\n ", random_integers_2d)
""" # np.random.normal(): Generates required number of "positive & Negative float values" in (1D / 2D arrays)"""
# Generate 5 random numbers from a normal distribution,
random_normal = np.random.normal(size=5)
# print("Random numbers from normal distribution (1D):", random_normal) # by default provides +ve/-Ve float values
# Generate a 2D array of shape (3, 3) with random numbers from a normal distribution
random_normal_2d = np.random.normal(size=(3, 3))
# print("Random numbers from normal distribution (2D):\n", random_normal_2d) # by default provides +ve/-Ve float values
""" np.random.rand(r, c) --> # Everytime generate only Random +ve float values in a given shape(r X c)--> r rows, c colums"""
random_of_values = np.random.rand(2,3) # generate Random values in a given shape(2X3)--> 2 rows ,3 colums
# print(random_of_values) # Bydefault It will give the random(float) valuesAuthor: Boyina Narendra
Supporting Author: M. Meera Sindhu
Request: If you find this information useful, please provide your valuable comments
No comments:
Post a Comment