NumPy_Array_Operations_and_Functions
NumPy_Array_Operations_and_Functions
1. Slicing an Array
2. Iterating over the elements
3. Modifying Array Values
Example Code:
import numpy as np
a = np.arange(10)
s = slice(2,10,2)
print(a[s])
Output
[2 4 6 8]
1|Page
Example Code 1:
import numpy as np
a = np.arange(10)
b = a[2:10:2]
print(b)
Output
[2 4 6 8]
The output is an array containing elements from index 2 to 10
(exclusive), with a step size of 2.
Example Code 2:
a = np.arange(30)
b = a[7]
print(b)
Output
7
The code slices single item at index 7 from a NumPy array created
with values 0 to 29 using arange().
Example Code 3:
Output
[2 3 4 5 6 7 8 9]
2|Page
The code creates a NumPy array a with values 0 to 6. It then prints
elements from index 3 onwards using print(a[3:]), resulting in the
output [3, 4, 5, 6].
Example Code:
import numpy as np
# Create a 2x3 array using arange() and reshape()
arr = np.arange(0, 30, 5).reshape(2, 3)
Output
Original array is:
[[ 0 5 10]
[15 20 25]]
The code creates a NumPy array (arr) using the arange function.
Array has values starting from 0, incrementing by 5, and stopping
before 30. The resulting 1-dimensional array is then reshaped into a
2x3 matrix using the reshape method. arr. nditer method is used to
iterate over each element and then print the whole array.
3|Page
3. Modifying Array Values: The nditer object features an additional
optional parameter known as op_flags. By default, it is set to read-
only, yet it can be configured to read-write or write-only mode. This
allows the modification of array elements through the iterator.
Example Code:
import numpy as np
arr = np.arange(0,60,5)
arr = arr.reshape(3,4)
print('Original array is:')
print(arr)
print('\n')
Output
Original array is:
[[ 0 5 10 15]
[20 25 30 35]
[40 45 50 55]]
The code creates a 1-dimensional array, reshape it into a 3x4 matrix, and
then iterates over the elements of the array using np.nditer to modify
each element by multiplying it by 2.
4|Page
Broadcasting is possible under the following conditions:
Example Code:
import numpy as np
arr1 = np.array([2,3,4,5])
arr2 = np.array([10,20,30,40])
arr3= arr1 * arr2
print(arr3)
Output
[ 20 60 120 200]
Two arrays named arr1 and arr2 are created. Elements of both arrays
are multiplied and the results are stored in arr3.
5|Page
Example 2:
import numpy as np
arr1 =
np.array([[10.0,10.0,10.0],[20.0,20.0,20.0],[30.0,30.0,
30.0],[40.0,40.0,40.0]])
arr2 = np.array([1.0,2.0,3.0])
print('First array:')
print(arr1)
print('\n')
print('Second array:')
print(arr2)
print('\n')
Output
First array:
[[10. 10. 10.]
[20. 20. 20.]
[30. 30. 30.]
[40. 40. 40.]]
Second array:
[1. 2. 3.]
Two arrays named arr1 and arr2 are created. The array arr1 is a 2D
array, and arr2 is a 1D array. Broadcasting is performed adding each
element of arr2 to the corresponding elements in each row of arr1.
6|Page
Broadcasting allows you to perform element-wise operations on
arrays of different shapes and sizes by automatically expanding the
smaller array to match the shape of the larger one. Let us learn
broadcasting iteration.
For example, if an array 'a' has dimensions 3x4, and another array 'b'
has dimensions 1x4, an iterator of the following kind is employed,
where array 'b' is broadcasted to the size of 'a'.
Example Code:
import numpy as np
arr = np.arange(0,60,5)
arr = arr.reshape(3,4)
Output
First array is:
[[ 0 5 10 15]
[20 25 30 35]
[40 45 50 55]]
7|Page
5:2
10:3
15:4
20:1
25:2
30:3
35:4
40:1
45:2
50:3
55:4
Now that you've become adept at iterating over arrays of both similar
and varying sizes, let's delve into performing operations on their
elements.
8|Page
Example Code:
import numpy as np
# Creating NumPy arrays
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
# Addition
result_add = np.add(a, b) # or a + b
print('Result of addition:',result_add)
# Subtraction
result_subtract = np.subtract(a, b) # or a - b
print('Result of subtraction:',result_subtract)
# Multiplication
result_multiply = np.multiply(a, b) # or a * b
print('Result of multiplication:',result_multiply)
# Division
result_divide = np.divide(a, b) # or a / b
print('Result after division:', result_divide)
Output
Result of addition: [5 7 9]
Result of subtraction: [-3 -3 -3]
Result of multiplication: [ 4 10 18]
Result after division: [0.25 0.4 0.5 ]
In the code, NumPy arrays a and b are created with values [1, 2, 3]
and [4, 5, 6]. The results of element-wise operations are stored in
result_add (addition), result_subtract (subtraction using
np.subtract or -), result_multiply (multiplication using np.multiply
or *), and result_divide (division using np.divide or /).
import numpy as np
angle = np.pi / 4 # 45 degrees in radians
9|Page
# Sine function
sin_val = np.sin(angle)
print(sin_val)
# Cosine function
cos_val = np.cos(angle)
print(cos_val)
# Tangent function
tan_val = np.tan(angle)
print(tan_val)
Output
0.7071067811865476
0.7071067811865476
0.9999999999999999
The code calculates and prints the sine, cosine, and tangent values
of a 45-degree angle (converted to radians).
import numpy as np
# Exponential function (e^x)
exp_val = np.exp(2)
print(exp_val)
# Logarithm base 10
log10_val = np.log10(100)
print(log10_val)
10 | P a g e
Output
7.38905609893065
2.0
4.605170185988092
# Mean
mean_val = np.mean(data)
print(mean_val)
# Median
median_val = np.median(data)
print(median_val)
# Standard deviation
std_dev = np.std(data)
print(std_dev)
Output
3.0
3.0
1.4142135623730951
The code computes and prints the mean, median, and standard
deviation of a NumPy array [1, 2, 3, 4, 5].
11 | P a g e
Linear Algebra with NumPy
Example Code:
# Matrix multiplication
matrix_a = np.array([[1, 2], [3, 4]])
matrix_b = np.array([[5, 6], [7, 8]])
result_matrix_multiply = np.dot(matrix_a, matrix_b)
print("Matrix Multiplication:")
print(result_matrix_multiply)
# Transpose of a matrix
result_transpose = np.transpose(matrix_a)
print("\nTranspose of Matrix A:")
print(result_transpose)
Output
Matrix Multiplication:
[[19 22]
[43 50]]
Transpose of Matrix A:
[[1 3]
[2 4]]
12 | P a g e
are solutions to the equation Av = λv, where A is the matrix, λ is the
eigenvalue, and v is the eigenvector.
• Eigenvectors are non-zero vectors that only change in scale
(scalar multiplication) when a linear transformation is applied to
them. They represent the directions in space that remain
unchanged under the transformation.
You can learn more about Eigenvalues and Eigenvectors from this
video- youtube.com/watch?v=PFDu9oVAE-g
Example Code:
# Import NumPy
import numpy as np
# Define a matrix
matrix_a = np.array([[1, 2], [3, 4]])
print("\nEigenvectors:")
print(eigenvectors)
Output
Eigenvalues:
[-0.37228132 5.37228132]
Eigenvectors:
[[-0.82456484 -0.41597356]
[ 0.56576746 -0.90937671]]
13 | P a g e
3. Solving Linear Equations: NumPy provides a function to solve
systems of linear equations.
# Import NumPy
import numpy as np
Output
Solution to the system of linear equations:
[-4.5 5. ]
14 | P a g e