How to install NumPy library in Python

NumPy stands for Numerical Python. This library deals with multi-dimensional arrays, matrices, and high-level mathematical functions. It is widely used by machine learning programmers, where they store data in the form of a NumPy array. As NumPy is designed in such a way that it supports parallel computations of an array, this feature enables the efficiency of the code.

In this Answer, we will discuss the installation of NumPy, and additionally, we will also look at the applications and functions provided by the NumPy library.

Installation of NumPy

Follow the below-mentioned steps to install NumPy on your system.

  • Make sure that Python is installed.

  • The installation of NumPy requires pip to be present in the system. To check for the presence of pip, run the following command.

pip --version
  • If the above commands return nothing or an error, then it means that pip needs to be installed. So to install the pip, run the following command.

python get-pip.py
  • Now that pip is installed, you can proceed to install NumPy using the below script.

pip install numpy
  • Once the installation is complete, you can start using NumPy in your Python projects by importing it in your code.

import numpy as np

Now we will look at some functions of the NumPy library.

Functions in NumPy

Some daily use and essential functions from the NumPy library are given below.

Array creation

As you must have an idea that NumPy deals explicitly with arrays. The examples in the code illustrate the initialization of an array. Have a look at the code. Comments are added to understand the code in a better way.

# Import NumPy library with the alias 'np'
import numpy as np
# Array Creation Functions
# Create a 1-dimensional array 'arr1' with elements [1, 2, 3, 4, 5]
arr1 = np.array([1, 2, 3, 4, 5])
# Create a 2-dimensional array 'arr2' (2x3) filled with zeros
arr2 = np.zeros((2, 3))
# Create a 2-dimensional array 'arr3' (3x2) filled with ones
arr3 = np.ones((3, 2))
# Create a 2-dimensional array 'arr4' (3x3) filled with the value 7
arr4 = np.full((3, 3), 7)
# Create a 1-dimensional array 'arr5' with elements from 0 to 10 (exclusive) with a step of 2 (i.e., [0, 2, 4, 6, 8])
arr5 = np.arange(0, 10, 2)
# Create a 1-dimensional array 'arr6' with 5 evenly spaced values between 0 and 1 (inclusive)
arr6 = np.linspace(0, 1, 5)
# Create a 3x3 identity matrix 'identity_matrix'
identity_matrix = np.eye(3)
# Print the content of the arrays using 'print' statements
print("Array 1:", arr1)
print("Zeros Array:", arr2)
print("Ones Array:", arr3)
print("Full Array:", arr4)
print("Arange Array:", arr5)
print("Linspace Array:", arr6)
print("Identity Matrix:")
print(identity_matrix)

Array manipulations

NumPy provides various functions such as reshaping, transposing, concatenating, and stacking arrays. These functions introduce ease while doing the coding.

import numpy as np
# Array Manipulation Functions
# Reshape 'arr1' into a 2-dimensional array with 5 rows and 1 column
arr7 = np.reshape(arr1, (5, 1))
# Transpose 'arr2', swapping rows and columns
arr8 = np.transpose(arr2)
# Concatenate 'arr2' and 'arr3' vertically (along rows)
arr9 = np.concatenate((arr2, arr3), axis=0)
# Split 'arr1' into two sub-arrays, each with half of the elements
arr10 = np.split(arr1, 2)
# Horizontally stack 'arr2' and 'arr3', joining them side by side
arr11 = np.hstack((arr2, arr3))
# Vertically stack 'arr2' and 'arr3', joining them on top of each other
arr12 = np.vstack((arr2, arr3))
# Print the results of array manipulations
print("Reshaped Array:", arr7)
print("Transposed Array:")
print(arr8)
print("Concatenated Array:")
print(arr9)
print("Split Arrays:", arr10)
print("Horizontally Stacked Array:")
print(arr11)
print("Vertically Stacked Array:")
print(arr12)

Mathematical functions

Mathematical functions provided in the NumPy library are given in the code below.

import numpy as np
# Mathematical Functions
# Add 2 to each element of 'arr1'
arr13 = np.add(arr1, 2)
# Multiply each element of 'arr1' by 3
arr14 = np.multiply(arr1, 3)
# Compute the sine of each element in 'arr1'
arr15 = np.sin(arr1)
# Compute the exponential (e^x) of each element in 'arr1'
arr16 = np.exp(arr1)
# Print the results of mathematical operations
print("Added 2:", arr13)
print("Multiplied by 3:", arr14)
print("Sine:", arr15)
print("Exponential:", arr16)

Statistical functions

We can perform statistical operations as well. In the code, comments provide a clear explanation of each statistical computation performed on the array arr1.

import numpy as np
# Statistical Functions
# Compute the mean of 'arr1'
mean_value = np.mean(arr1)
# Compute the median of 'arr1'
median_value = np.median(arr1)
# Compute the standard deviation of 'arr1'
std_value = np.std(arr1)
# Compute the variance of 'arr1'
var_value = np.var(arr1)
# Compute the sum of elements in 'arr1'
sum_value = np.sum(arr1)
# Find the minimum value in 'arr1'
min_value = np.min(arr1)
# Find the maximum value in 'arr1'
max_value = np.max(arr1)
# Print the results of statistical computations
print("Mean:", mean_value)
print("Median:", median_value)
print("Standard Deviation:", std_value)
print("Variance:", var_value)
print("Sum:", sum_value)
print("Minimum:", min_value)
print("Maximum:", max_value)

Linear algebra

In deep learning, we acquire linear algebra operations for efficient computations while building a neural network. Have a look at the code for the functions provided by NumPy and being used in making the machine learning models:

import numpy as np
# Linear Algebra Functions
# Define a 2x2 matrix 'matrix1'
matrix1 = np.array([[1, 2], [3, 4]])
# Define another 2x2 matrix 'matrix2'
matrix2 = np.array([[2, 0], [1, 3]])
# Compute the dot product of 'matrix1' and 'matrix2'
dot_product = np.dot(matrix1, matrix2)
# Compute the matrix product of 'matrix1' and 'matrix2'
matrix_product = np.matmul(matrix1, matrix2)
# Compute the inverse of 'matrix1'
inverse_matrix = np.linalg.inv(matrix1)
# Compute the determinant of 'matrix1'
determinant = np.linalg.det(matrix1)
# Compute the eigenvalues and eigenvectors of 'matrix1'
eigenvalues, eigenvectors = np.linalg.eig(matrix1)
# Print the results of linear algebra computations
print("Dot Product:")
print(dot_product)
print("Matrix Product:")
print(matrix_product)
print("Inverse Matrix:")
print(inverse_matrix)
print("Determinant:", determinant)
print("Eigenvalues:")
print(eigenvalues)
print("Eigenvectors:")
print(eigenvectors)

Random number generation

Random number generation serves various essential purposes in various fields, including scientific computing, simulations, statistics, cryptography, gaming, and more. So for this, NumPy is useful in this domain by providing the below-mentioned functions.

import numpy as np
# Random Number Generation Functions
# Generate a 3x2 array with random numbers from a uniform distribution [0, 1)
random_uniform = np.random.rand(3, 2)
# Generate a 3x2 array with random numbers from a standard normal distribution (mean=0, std=1)
random_normal = np.random.randn(3, 2)
# Generate a 2x3 array with random integers between 0 and 9
random_integers = np.random.randint(0, 10, size=(2, 3))
# Generate a single random number from a uniform distribution [0, 1)
random_uniform_single = np.random.random()
# Generate an array of size 3 with random elements sampled from the given array [1, 2, 3, 4, 5]
random_choice = np.random.choice([1, 2, 3, 4, 5], size=3)
# Print the results of random number generations
print("Random Uniform:")
print(random_uniform)
print("Random Normal:")
print(random_normal)
print("Random Integers:")
print(random_integers)
print("Random Uniform Single:")
print(random_uniform_single)
print("Random Choice:")
print(random_choice)

Conclusion

NumPy is a resourceful library if an individual wants to perform a numerical computation. However, it also provides additional features of statistical computations, solving problems related to linear algebra. Also, the random function generation adds beauty while initializing the weights in a neural network.

Note: NumPy supports numerical computation, if you want to perform symbolic computations you can use SymPy.

Q

How can you create a 3x3 identity matrix using NumPy?

A)

np.identity_matrix(3)

B)

np.eye(3)

C)

np.ones(3, 3)

D)

np.zeros(3, 3)

Copyright ©2024 Educative, Inc. All rights reserved