Data Analysis with SciPy - GeeksforGeeks
Statistics (scipy.stats) — SciPy v1.11.1 Manual
Scipy is a Python-based ecosystem of open-source software for mathematics, science, and engineering. It is built on top of the NumPy library and provides a collection of algorithms and functions for numerical integration, optimization, signal and image processing, linear algebra, and more. Scipy is widely used in scientific computing and data analysis.
Here are some of the areas where Scipy can be used:
Before using Scipy, you need to install it using pip
or conda
. Once installed, you can import the library and its submodules in your Python script or Jupyter notebook:
import scipy
from scipy import optimize, integrate, interpolate, signal, linalg
Here are some examples of how to use Scipy:
Optimization: Find the minimum of a function using the Broyden-Fletcher-Goldfarb-Shanno (BFGS) algorithm:
def f(x):
return x**2 - 4*x + 3
result = optimize.minimize(f, x0=0)
print(result)
Integration: Integrate a function numerically:
from numpy import sin, cos
def f(x):
return sin(x)
result = integrate.quad(f, 0, 2*cos(1))
print(result)
Interpolation: Interpolate a set of points to find a function that passes through them:
import matplotlib.pyplot as plt
x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]
f = interpolate.interp1d(x, y, kind='cubic')
xnew = [0.5, 1.5, 2.5, 3.5]
ynew = f(xnew)
plt.plot(x, y, 'o', xnew, ynew, '-')
plt.show()
Signal and Image Processing: Filter a signal using a Butterworth filter:
from scipy import signal
import numpy as np
import matplotlib.pyplot as plt
# Generate a noisy signal
t = np.linspace(0, 10, 1000)
x = np.sin(t) + 0.1*np.random.randn(len(t))
# Filter the signal using a Butterworth filter
b, a = signal.butter(4, 0.1, 'low')
y = signal.filtfilt(b, a, x)
# Plot the original and filtered signal
fig, (ax0, ax1) = plt.subplots(nrows=2)
ax0.plot(t, x, 'b')
ax0.set_title('Original signal')
ax1.plot(t, y, 'r')
ax1.set_title('Filtered signal')
plt.show()