-
-
Save jayluxferro/676795504fbcf4001c010efa9e65ab31 to your computer and use it in GitHub Desktop.
How to do time derivatives of a pandas Series using NumPy 1.13 gradient
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import pandas as pd | |
%matplotlib inline | |
import matplotlib.pyplot as plt | |
# Base time series | |
base_t = pd.date_range("2017-07-20 11:00", "2017-07-20 12:00", freq="T") | |
# We add some random noise to achieve non uniform spacing | |
t = base_t + pd.to_timedelta(5 * np.random.randn(len(base_t)), unit='s') | |
assert t.is_monotonic_increasing | |
# Extract numerical values | |
values = (t - t[0]).total_seconds() | |
# My function | |
y = pd.Series(np.cos(0.1 * values)) | |
# Derivative! Requires NumPy >= 1.13 | |
# https://docs.scipy.org/doc/numpy/reference/generated/numpy.gradient.html#numpy.gradient | |
dy = np.gradient(y, values) | |
# Plotting | |
fig, ax = plt.subplots(2, sharex=True, figsize=(6, 6)) | |
ax[0].plot(t, y) | |
ax[1].plot(t, dy, color="C1") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment