Skip to content

Instantly share code, notes, and snippets.

@FerusAndBeyond
Created April 21, 2022 19:59
Show Gist options
  • Save FerusAndBeyond/9bf24f128a86fdb3de20a37837e03861 to your computer and use it in GitHub Desktop.
Save FerusAndBeyond/9bf24f128a86fdb3de20a37837e03861 to your computer and use it in GitHub Desktop.
Cross-correlation part2
from scipy.signal import correlate
from scipy.signal import correlation_lags
# Function to calculate cross-correlation,
# extract the best matching shift and then shift
# one of the series appropriately.
def shift_for_maximum_correlation(x, y):
correlation = correlate(x, y, mode="full")
lags = correlation_lags(x.size, y.size, mode="full")
lag = lags[np.argmax(correlation)]
print(f"Best lag: {lag}")
if lag < 0:
y = y.iloc[abs(lag):].reset_index(drop=True)
else:
x = x.iloc[lag:].reset_index(drop=True)
return x, y
# Plot results after shifting
for x, y in shifted_versions:
shifted_x, shifted_y = shift_for_maximum_correlation(x, y)
plot_correlation(shifted_x, shifted_y, text="after shifting")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment