What is the use of the SciPy library in Python?

The SciPy library is used for technical computations. It builds upon another library called NumPy. It helps us solve mathematical problems, optimize functions, process signals and images, analyze data statistically, etc. This Answer discusses the installation and applications of the SciPy library.

Installation of SciPy

To install SciPy, you need to have Python installed on your computer. As discussed earlier, SciPy relies on another library called NumPy, so ensure you also have NumPy installed. Commands to install NumPy and SciPy are given below.

pip3 install numpy

Applications of SciPy

The Scipy library in Python has a notable and wide range of applications across various technical and scientific fields. Some of the uses of SciPy are represented below. In this Answer, we discuss all these applications individually and understand the code.

Applications of SciPy
Applications of SciPy

Numerical interpolation

Numerical interpolation allows us to estimate the values of a function at points between known data points. The code below performs numerical interpolation using the interp1d function from SciPy. It approximates the value of the function y at a specific point x_new using linear interpolation.

The output of the below code will be the interpolated value of the sine function at x = 4.5.

import numpy as np
from scipy.interpolate import interp1d
x = np.linspace(0, 10, 11)
y = np.sin(x)
f = interp1d(x, y, kind='linear')
x_new = 4.5
y_new = f(x_new)
print("Interpolated Value at x =", x_new, ":", y_new)

Optimization

We can perform optimization with the help of the minimize function provided in the SciPy library. In the code below, we are finding the minimum value of the objective function x**2 + 3*x + 5 .

from scipy.optimize import minimize
def objective_function(x):
return x**2 + 3*x + 5
result = minimize(objective_function, x0=0)
print("Optimization Result:", result.x)

Sparse linear system

Sparse linear systems refer to systems of linear equations where the coefficient matrix is sparse and contains mainly zero elements. Sparse matrices are more memory-efficient and allow efficient computations in cases where most elements are zero. In the code, the spsolve function efficiently solves the sparse linear system Ax = b using a suitable solver for sparse matrices.

import numpy as np
from scipy.sparse import csc_matrix
from scipy.sparse.linalg import spsolve
# Create a sparse matrix
data = np.array([2, 3, 1, 4])
row_indices = np.array([0, 1, 2, 3])
col_indices = np.array([0, 1, 2, 3])
A_sparse = csc_matrix((data, (row_indices, col_indices)), shape=(4, 4))
# Create the right-hand side vector
b = np.array([10, 20, 15, 25])
# Solve the linear system Ax = b
x = spsolve(A_sparse, b)
print("Solution to Ax = b:", x)

Linear algebra

With SciPy, we can perform a LU (lower-upper) decomposition using the SciPy library in Python. The LU decomposition is a factorization of a square matrix into three matrices: a permutation matrix (P), a lower triangular matrix (L), and an upper triangular matrix (U).

import numpy as np
from scipy.linalg import lu
A = np.array([[2, 1], [1, 3]])
P, L, U = lu(A)
print("LU Decomposition:")
print("P matrix:", P)
print("L matrix:", L)
print("U matrix:", U)

Signal processing

We use the SciPy library for signal processing also. The code applies a low-pass Butterworth filter to a sample signal to remove high-frequency noise and retain the lower-frequency components. Run the code below and look at the output for visualization.

import numpy as np
from scipy import signal
# Create a sample signal
t = np.linspace(0, 1, 1000)
signal_input = np.sin(2 * np.pi * 5 * t) + 0.5 * np.random.randn(len(t))
# Apply a low-pass Butterworth filter
b, a = signal.butter(4, 0.08, 'low')
filtered_signal = signal.filtfilt(b, a, signal_input)
# Plot the original and filtered signals
import matplotlib.pyplot as plt
plt.plot(t, signal_input, label='Original Signal')
plt.plot(t, filtered_signal, label='Filtered Signal')
plt.legend()
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.savefig("./output/Plot.png")
plt.show()

Statistics

The SciPy library in Python provides various statistical functions and tools for various statistical computations. We compute the mean, standard deviation, z-score, and p-value in the following code.

import numpy as np
from scipy.stats import norm
data = np.random.normal(0, 1, size=1000)
mean = np.mean(data)
std_dev = np.std(data)
z_score = (1.5 - mean) / std_dev
p_value = 1 - norm.cdf(z_score)
print("Mean:", mean)
print("Standard Deviation:", std_dev)
print("Z-score:", z_score)
print("P-value:", p_value)

Fourier transforms

A Fourier transform allows us to analyze a signal regarding its frequency components. The transform converts a signal from its original time or spatial domain representation into a representation in the frequency domain. The code computes the inverse Fourier transform of the Fourier-transformed signal using scipy.fft.ifft() to reconstruct the original signal.

import numpy as np
from scipy.fft import fft, ifft
import matplotlib.pyplot as plt
# Generate a sample signal
t = np.linspace(0, 2*np.pi, 1000)
signal = np.sin(5 * t) + 0.5 * np.sin(20 * t)
# Compute the Fourier transform
fourier_transform = fft(signal)
# Compute the inverse Fourier transform
reconstructed_signal = ifft(fourier_transform)
# Plot the original signal and the reconstructed signal
plt.plot(t, signal, label='Original Signal')
plt.plot(t, reconstructed_signal, label='Reconstructed Signal')
plt.legend()
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.title('Original and Reconstructed Signals')
plt.savefig("./output/Plot.png")
plt.show()

Differential equations

Differential equations describe how a function changes concerning one or more independent variables. The solve_ivp function from SciPy is used to numerically solve the ODE defined by differential_equation. The initial condition y0 and the time span t_span are provided as arguments. The t_eval parameter specifies the time points to evaluate the solution and np.linspace(0, 5, 100) generates 100 equally spaced time points between 0 and 5.

import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
# Define the differential equation dy/dt = -2*y
def differential_equation(t, y):
return -2 * y
# Initial condition
y0 = 1
# Time points for solution
t_span = [0, 5]
# Solve the differential equation
sol = solve_ivp(differential_equation, t_span, [y0], t_eval=np.linspace(0, 5, 100))
# Plot the solution
plt.plot(sol.t, sol.y[0])
plt.xlabel('Time')
plt.ylabel('y(t)')
plt.title('Solution of dy/dt = -2*y')
plt.savefig("./output/Plot.png")
plt.show()

Image processing

The primary application of the SciPy library is in image processing. The following code creates a sample image with random noise and then applies a Gaussian filter to smooth the image. The ndimage.gaussian_filter() function applies a Gaussian filter to the input image with a specified standard deviation.

import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage
# Create a sample image with random noise
image = np.random.random((100, 100))
# Apply Gaussian filter for smoothing
filtered_image = ndimage.gaussian_filter(image, sigma=2)
# Display the original and filtered images
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(filtered_image, cmap='gray')
plt.title('Filtered Image')
plt.axis('off')
plt.savefig("./output/Plot.png")
plt.show()

Discrete cosine transform

The scipy.fft.dct() function computes the Discrete Cosine Transform of the input signal. The result, stored in dct_result, represents the signal in the frequency domain as a set of cosine wave components. The output will be a plot displaying both the original and reconstructed signals.

import numpy as np
from scipy.fft import dct
# Create a sample signal
x = np.linspace(0, 2 * np.pi, 16)
signal = np.sin(x)
# Compute the DCT
dct_result = dct(signal)
# Inverse DCT to reconstruct the original signal
reconstructed_signal = dct(dct_result, type=3)
# Plot the original and reconstructed signals
import matplotlib.pyplot as plt
plt.plot(x, signal, label='Original Signal')
plt.plot(x, reconstructed_signal, label='Reconstructed Signal')
plt.legend()
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.title('Original and Reconstructed Signals')
plt.savefig("./output/Plot.png")
plt.show()

Conclusion

SciPy allows researchers, engineers, and data scientists to perform various computations efficiently. With the help of it, we can solve differential equations, manipulate arrays, work with sparse matrices, and much more. Its extensive functionality makes it an essential and valuable tool.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved