Numpy Library in Python

Rina Mondal
6 min readDec 25, 2023

--

NumPy is a powerful numerical computing library in Python. It provides a wide range of functions for working with arrays, matrices, mathematical operations, linear algebra, and more. Numpy module is to be imported for performing any numpy operations.

Why Numpy was required when we already had many data types in Python ??

Python is popular for its easy syntax, but it can be slow compared to other languages due to its handling of various data types. Its built-in data types, which hold heterogeneous data and referential addresses, result in slowness.

The NumPy library addresses this issue by handling only homogeneous data, significantly increasing processing speed. This efficiency has made Python more popular in data science, allowing for faster computations and handling of large datasets.

Here are some commonly used NumPy functions:

Create an array:

Create an array containing 5 values in arr variable:

arr = np.array([1, 2, 3, 4, 5])
print("Array:", arr)
Array: [1 2 3 4 5]

Create an array filled with zeros:

zeros_arr = np.zeros((3, 2))
print("Zeros Array:\n", zeros_arr)
O/t- Zeros Array:
[[0. 0.]
[0. 0.]
[0. 0.]]

Create an array filled with ones:

ones_arr = np.ones((3, 2))
print("Ones Array:\n", ones_arr)
O/t- Ones Array:
[[1. 1.]
[1. 1.]
[1. 1.]]

Create an array with regularly spaced values:

# Create an array with regularly spaced values
range_arr = np.arange(0, 10, 2)
print("Range Array:", range_arr)
O/t- Range Array: [0 2 4 6 8]

5. Create an array with a specified number of evenly spaced values:

linspace_arr = np.linspace(0, 1, 5)
print("Linspace Array:", linspace_arr)
O/t- Linspace Array: [0. 0.25 0.5 0.75 1. ]

Array Operations:
1. Return the dimensions of an array:

# Dimensions of an array
arr = np.array([[1, 2, 3], [4, 5, 6]])
shape = np.shape(arr)
print("Shape of Array:", shape)
O/t- Shape of Array: (2, 3)

2. Reshape an array:

# Reshape an array
reshaped_arr = np.reshape(arr,(3, 2))
print("Reshaped Array:\n", reshaped_arr)
O/t- Reshaped Array:
[[1 2]
[3 4]
[5 6]]

3. Join arrays along an existing axis.

# Creating two-dimensional arrays
array1 = np.array([[1, 2], [3, 4]])
array2 = np.array([[5, 6]])

# Concatenating along axis 0 (rows)
concatenated_rows = np.concatenate((array1, array2), axis=0)
print("Concatenated along rows:\n", concatenated_rows)
# Output:
# [[1 2]
# [3 4]
# [5 6]]

# Concatenating along axis 1 (columns)
concatenated_columns = np.concatenate((array1, array2.T), axis=1)
print("\nConcatenated along columns:\n", concatenated_columns)
# Output:
# [[1 2 5]
# [3 4 6]]

4. Split an array into multiple sub arrays:

import numpy as np

# Creating an array
original_array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

# Splitting the array into three subarrays
subarrays = np.split(original_array, [3, 7])

# Displaying the result
for i, subarray in enumerate(subarrays):
print(f"Subarray {i + 1}: {subarray}")
O/t- Subarray 1: [1 2 3]
Subarray 2: [4 5 6 7]
Subarray 3: [ 8 9 10]

Mathematical Operations:

Element-wise operations, Aggregate Functions, Array Statistics


# Element-wise operations
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
addition = np.add(a, b)
multiplication=np.add (a,b)

# Aggregate functions
sum_a = np.sum(a)

# Array statistics
mean_b=np.mean(b)
min_a = np.min(a)
max_b = np.max(b)

print("Element-wise Addition:", addition)
print("Element-wise Multiplication:", multiplication)
print("Sum of Array 'a':", sum_a)
print("Mean of Array 'b':", mean_b)
print("Minimum of Array 'a':", min_a)
print("Maximum of Array 'b':", max_b)
O/t- Element-wise Addition: [5 7 9]
Element-wise Multiplication: [5 7 9]
Sum of Array 'a': 6
Mean of Array 'b': 5.0
Minimum of Array 'a': 1
Maximum of Array 'b': 6

Linear Algebra operations:

1. numpy.dot: Dot product of two arrays.
2. numpy.transpose: Transpose of an array.
3. numpy.linalg.inv: Inverse of a matrix.
4. numpy.linalg.det: Determinant of a matrix.

# Example 1: Dot product of two arrays
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
dot_product = np.dot(array1, array2)
print("Dot Product:", dot_product)

# Example 2: Transpose of a 2-D array
matrix = np.array([[1, 2, 3], [4, 5, 6]])
transposed_matrix = np.transpose(matrix)
print("\nOriginal Matrix:\n", matrix)
print("Transposed Matrix:\n", transposed_matrix)

# Example 3: Inverse of a matrix
matrix_to_inverse = np.array([[4, 7], [2, 6]])
inverse_matrix = np.linalg.inv(matrix_to_inverse)
print("\nOriginal Matrix:\n", matrix_to_inverse)
print("Inverse Matrix:\n", inverse_matrix)

# Example 4: Determinant of a matrix
matrix_to_determine_det = np.array([[4, 7], [2, 6]])
determinant = np.linalg.det(matrix_to_determine_det)
print("\nMatrix:\n", matrix_to_determine_det)
print("Determinant:", determinant)
O/t- Dot Product: 32
Original Matrix:
[[1 2 3]
[4 5 6]]
Transposed Matrix:
[[1 4]
[2 5]
[3 6]]
Original Matrix:
[[4 7]
[2 6]]
Inverse Matrix:
[[ 0.6 -0.7]
[-0.2 0.4]]
Matrix:
[[4 7]
[2 6]]
Determinant: 10.000000000000002

Generate Random Values:

  1. Generate random values in a given shape.
  2. Generate random values from a standard normal distribution.
  3. Generate random integers.
# Example 1: Generate random values in a given shape
shape = (3, 2) # 3 rows, 2 columns
random_array = np.random.random(shape)
print("Random Values in Given Shape:\n", random_array)

# Example 2: Generate random values from a standard normal distribution
shape = (2, 3) # 2 rows, 3 columns
random_normal_array = np.random.randn(*shape)
print("\nRandom Values from Standard Normal Distribution:\n", random_normal_array)

# Example 3: Generate random integers
low_limit = 1
high_limit = 10
shape = (2, 3) # 2 rows, 3 columns
random_integers = np.random.randint(low_limit, high_limit + 1, size=shape)
print("\nRandom Integers:\n", random_integers)
O/t- Random Values in Given Shape:
[[0.06576373 0.83019688]
[0.39124613 0.59384333]
[0.26858389 0.04255203]]
Random Values from Standard Normal Distribution:
[[-1.41301123 0.30455647 1.68145806]
[ 0.9579506 -1.02050267 -0.43563988]]
Random Integers:
[[9 7 2]
[3 2 8]]

Trigonometric Functions:

# Trigonometric functions
angle_in_degrees = 30

# Convert angle to radians
angle_in_radians = np.radians(angle_in_degrees)

sin_value = np.sin(angle_in_radians)
cos_value = np.cos(angle_in_radians)
tan_value = np.tan(angle_in_radians)

print(f"Trigonometric Functions for {angle_in_degrees} degrees:")
print(f"sin({angle_in_degrees} degrees) =", sin_value)
print(f"cos({angle_in_degrees} degrees) =", cos_value)
print(f"tan({angle_in_degrees} degrees) =", tan_value)

# Inverse trigonometric functions
value_for_inverse_functions = 0.5

arcsin_value = np.arcsin(value_for_inverse_functions)
arccos_value = np.arccos(value_for_inverse_functions)
arctan_value = np.arctan(value_for_inverse_functions)

# Convert angles to degrees
arcsin_value_degrees = np.degrees(arcsin_value)
arccos_value_degrees = np.degrees(arccos_value)
arctan_value_degrees = np.degrees(arctan_value)

#Hyperbolic sin function
x = 1.0
sinh_result = np.sinh(x)


print(f"\nInverse Trigonometric Functions for {value_for_inverse_functions}:")
print(f"arcsin({value_for_inverse_functions}) =", arcsin_value, "radians or", arcsin_value_degrees, "degrees")
print(f"arccos({value_for_inverse_functions}) =", arccos_value, "radians or", arccos_value_degrees, "degrees")
print(f"arctan({value_for_inverse_functions}) =", arctan_value, "radians or", arctan_value_degrees, "degrees")
print(sinh_result)
O/t- 
Trigonometric Functions for 30 degrees:
sin(30 degrees) = 0.49999999999999994
cos(30 degrees) = 0.8660254037844387
tan(30 degrees) = 0.5773502691896257
Inverse Trigonometric Functions for 0.5:
arcsin(0.5) = 0.5235987755982989 radians or 30.000000000000004 degrees
arccos(0.5) = 1.0471975511965979 radians or 60.00000000000001 degrees
arctan(0.5) = 0.4636476090008061 radians or 26.56505117707799 degrees
Sinh result 1.1752011936438014

Statistical Functions:

1. numpy.percentile: Compute the q-th percentile.
2. Compute the median of an array.

# Generate a random array
random_array = np.random.randint(1, 100, size=10)
print("Original Array:", random_array)


# Compute the median of the array
median_value = np.median(random_array)
print("\nMedian:", median_value)


# Compute the 25th and 75th percentiles
percentile_25 = np.percentile(random_array, 25)
percentile_75 = np.percentile(random_array, 75)


print("\n25th Percentile:", percentile_25)
print("75th Percentile:", percentile_75)

Array Comparison:

1. Element-wise comparison functions:

# Create two arrays for comparison
array1 = np.array([1, 2, 3])
array2 = np.array([1, 2, 4])

# Element-wise comparison functions
equal_result = np.equal(array1, array2)
not_equal_result = np.not_equal(array1, array2)
greater_result = np.greater(array1, array2)
greater_equal_result = np.greater_equal(array1, array2)
less_result = np.less(array1, array2)
less_equal_result = np.less_equal(array1, array2)

# Displaying the results
print("Array 1:", array1)
print("Array 2:", array2)

print("\nElement-wise Comparisons:")
print("Equal:", equal_result)
print("Not Equal:", not_equal_result)
print("Greater Than:", greater_result)
print("Greater Than or Equal:", greater_equal_result)
print("Less Than:", less_result)
print("Less Than or Equal:", less_equal_result)
O/t - Array 1: [1 2 3]
Array 2: [1 2 4]
Element-wise Comparisons:
Equal: [ True True False]
Not Equal: [False False True]
Greater Than: [False False False]
Greater Than or Equal: [ True True False]
Less Than: [False False True]
Less Than or Equal: [ True True True]

These are just a few examples, and NumPy provides many more functions for efficient numerical operations. It’s a fundamental library for data manipulation and scientific computing in Python.

Explore Data Science Roadmap.

Complete Explanation of Numpy Library in my YouTube Channel For Free.

Give it :👏👏👏👏:
If you found this guide helpful , why not show some love? Give it a Clap 👏, and if you have questions or topics you’d like to explore further, drop a comment 💬 below 👇

--

--

Rina Mondal

I have an 8 years of experience and I always enjoyed writing articles. If you appreciate my hard work, please follow me, then only I can continue my passion.