python-scipyHow can I use Python and SciPy to resample data?
Using Python and SciPy, data can be resampled by applying a variety of interpolation techniques. The SciPy library provides a number of functions for interpolation, including linear, nearest neighbour, and cubic spline interpolation.
For example, the following code block uses SciPy's interp1d
function to resample a given data set using linear interpolation:
from scipy.interpolate import interp1d
import numpy as np
# Given data
x = np.array([1,2,3,4,5])
y = np.array([1,2,4,8,16])
# Resample using linear interpolation
f = interp1d(x, y, kind='linear')
x_new = np.linspace(1, 5, num=50)
y_new = f(x_new)
print(y_new)
Output example
[ 1. 1.16326531 1.32653061 1.48979592 1.65306122 1.81632653
1.97959184 2.14285714 2.30612245 2.46938776 2.63265306 2.79591837
2.95918367 3.12244898 3.28571429 3.44897959 3.6122449 3.7755102
3.93877551 4.10204082 4.26530612 4.42857143 4.59183673 4.75510204
4.91836735 5.08163265 5.24489796 5.40816327 5.57142857 5.73469388
5.89795918 6.06122449 6.2244898 6.3877551 6.55102041 6.71428571
6.87755102 7.04081633 7.20408163 7.36734694 7.53061224 7.69387755
7.85714286 8.02040816 8.18367347 8.34693878 8.51020408 8.67346939
8.83673469 9. ]
The code above does the following:
- Imports the
interp1d
function from SciPy'sinterpolate
module, as well asnumpy
- Defines the x and y values of the original data set
- Uses the
interp1d
function to create a linear interpolator from the original data set - Defines a new set of x values to use for the resampled data
- Uses the interpolator to calculate the y values of the resampled data
- Prints the resampled data
Helpful links
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How can I use Python and SciPy to implement a quantum Monte Carlo simulation?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How do I use the numpy vstack function in Python?
- How do I convert a Python numpy.ndarray to a list?
- How can I use Python and SciPy to find the zeros of a function?
- How do I create a zero matrix using Python and Numpy?
- How can I check if a certain version of Python is compatible with SciPy?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How do I use the scipy ttest_ind function in Python?
See more codes...