NumPy Arrays: Core Operations
Basic Operations
The basic operations which can be performed on arrays are:
1. Slicing an Array
2. Reshaping
3. Element-wise Operations
1. Slicing an Array: Array slicing is used to extract a portion of an array.
Slicing is a powerful and efficient way to manipulate arrays in Python.
Slicing can be done in two ways:
a. Using slice() function
b. Using indices
a. Using slice() function: The slice() function takes three parameters:
start, stop, and step, and returns a slice object that represents the
set of indices specified by these parameters.
Example Code:
import numpy as np
a = [Link](10)
s = slice(2,10,2)
print(a[s])
Output
[2 4 6 8]
The code snippet creates an array named a, with values ranging
from 0 to 9. It then defines a slice object s with a start index of 2,
stop index of 10, and step size of 2.
b. Using Indices: Array can be sliced using parameters separated
by a colon (start:stop:step).
1 | Page
Example Code 1:
import numpy as np
a = [Link](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:
# slice single item
import numpy as np
a = [Link](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().
In this code snippet, a NumPy array a is created using [Link](30),
generating an array with values from 0 to 29. The variable b is
assigned the value at index 7 of the array a. Since indexing starts
from 0, this corresponds to the eighth element in the array. The
output of the code will be the value at index 7 of the array a, which is
7. Therefore, running the code will print 7 to the console.
2. Reshaping an Array: Reshaping NumPy arrays involves changing the
shape or dimensions of the array without altering its data content. This
can be useful for tasks such as converting between different
dimensional arrays or preparing data for specific computations.
NumPy provides the reshape() method to perform array reshaping.
Let us learn to iterate and reshape an array.
2 | Page
Iterating over Numpy arrays: The NumPy package includes an
efficient multidimensional iterator object called [Link]. It allows
iteration over an array using Python's standard Iterator interface.
Example Code:
import numpy as np
# Create a 2x3 array using arange() and reshape()
arr = [Link](0, 30, 5).reshape(2, 3)
print('Original array is:')
print(arr)
print('\n')
print('Modified array is:')
for x in [Link](arr):
print(x)
Output
Original array is:
[[ 0 5 10]
[15 20 25]]
Modified 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. Element-wise Operations: Element-wise operations involve
performing operations on corresponding elements of arrays. This
means that when you perform an operation (such as addition,
subtraction, multiplication, division, etc.) between two arrays, the
3 | Page
operation is applied to each pair of elements at the same position in
the arrays.
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 = [Link](0,60,5)
arr = [Link](3,4)
print('Original array is:')
print(arr)
print('\n')
for x in [Link](arr, op_flags = ['readwrite']):
x[...] = 2*x
print('Modified array is:')
print(arr)
Output
Original array is:
[[ 0 5 10 15]
[20 25 30 35]
[40 45 50 55]]
Modified array is:
[[ 0 10 20 30]
[ 40 50 60 70]
[ 80 90 100 110]]
The code creates a 1-dimensional array, reshape it into a 3x4 matrix, and
then iterates over the elements of the array using [Link] to modify
each element by multiplying it by 2.
In NumPy, a comprehensive set of mathematical functions is available for
performing various operations on arrays. These functions enable efficient
and vectorised computation, making them essential for scientific
computing and data analysis.
4 | Page
Mathematical Functions in NumPy
The following mathematical functions can be applied on arrays:
1. Basic Mathematical Operation
2. Trigonometric Functions:
3. Exponential and Logarithmic Functions
4. Statistical Functions
1. Basic Mathematical Operations: NumPy allows you to perform
basic arithmetic operations on arrays like addition, subtraction,
multiplication, and division.
Example Code:
import numpy as np
# Creating NumPy arrays
a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])
# Addition
result_add = [Link](a, b) # or a + b
print('Result of addition:',result_add)
# Subtraction
result_subtract = [Link](a, b) # or a - b
print('Result of subtraction:',result_subtract)
# Multiplication
result_multiply = [Link](a, b) # or a * b
print('Result of multiplication:',result_multiply)
# Division
result_divide = [Link](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]
5 | Page
and [4, 5, 6]. The results of element-wise operations are stored in
result_add (addition), result_subtract (subtraction using [Link]
or -), result_multiply (multiplication using [Link] or *), and
result_divide (division using [Link] or /).
2. Trigonometric Functions: NumPy provides trigonometric functions
for working with angles.
import numpy as np
angle = [Link] / 4 # 45 degrees in radians
# Sine function
sin_val = [Link](angle)
print(sin_val)
# Cosine function
cos_val = [Link](angle)
print(cos_val)
# Tangent function
tan_val = [Link](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).
3. Exponential and Logarithmic Functions:
● [Link](x) computes the element-wise exponential of an array x.
● [Link](x) computes the element-wise natural logarithm of an
array x.
● np.log10(x) computes the element-wise logarithm to the base 10 of
an array x.
6 | Page
import numpy as np
# Exponential function (e^x)
exp_val = [Link](2)
print(exp_val)
# Logarithm base 10
log10_val = np.log10(100)
print(log10_val)
# Natural logarithm (base e)
log_val = [Link](100)
print(log_val)
Output
7.38905609893065
2.0
4.605170185988092
The code calculates and prints the exponential of 2, the base-10
logarithm of 100, and the natural logarithm of 100 using NumPy.
4. Statistical Functions: These are the operations that provide summary
statistics and insights into the characteristics of a dataset.
Function Description Example Usage
mean Computes the arithmetic [Link](array,
mean along the specified axis axis=None)
median Computes the median along [Link](array,
the specified axis axis=None)
std Computes the standard [Link](array,
deviation along the specified axis=None)
axis
var Computes the variance along [Link](array,
the specified axis axis=None)
sum Computes the sum of array [Link](array,
elements along the specified axis=None)
axis
7 | Page
min Computes the minimum [Link](array,
value along the specified axis axis=None)
max Computes the maximum [Link](array,
value along the specified axis axis=None)
Example Code:
data = [Link]([1, 2, 3, 4, 5])
# Mean
mean_val = [Link](data)
print(mean_val)
# Median
median_val = [Link](data)
print(median_val)
# Standard deviation
std_dev = [Link](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].
a. Creating NumPy array:
data = [Link]([1, 2, 3, 4, 5])
This line creates a NumPy array named data containing the
values [1, 2, 3, 4, 5].
b. Calculating Mean
# Mean
mean_val = [Link](data)
print(mean_val)
8 | Page
This section calculates the mean of the data array using
[Link](). The [Link]() function computes the arithmetic
mean along the specified axis, or of the flattened array if no axis
is specified. In this case, it calculates the mean of all values in
the data array and assigns the result to the variable mean_val.
Then, it prints the mean value.
c. Calculating Median
# Median
median_val = [Link](data)
print(median_val)
This part computes the median of the data array using
[Link](). The [Link]() function calculates the median
along the specified axis, or of the flattened array if no axis is
specified. Similar to the mean calculation, it computes the
median of all values in the data array and assigns the result to
the variable median_val. Then, it prints the median value.
d. Calculating Standard Deviation
# Standard deviation
std_dev = [Link](data)
print(std_dev)
This section computes the standard deviation of the data array
using [Link](). The [Link]() function calculates the standard
deviation along the specified axis, or of the flattened array if no
axis is specified. It computes the standard deviation of all values
in the data array and assigns the result to the variable std_dev.
Then, it prints the standard deviation value.
9 | Page