[Python] Numpy.correlate returns incorrect value

Discussão em 'Python' iniciado por Stack, Janeiro 24, 2025.

  1. Stack

    Stack Membro Participativo

    Sorry, first timer.

    I am trying to verify cross correlation between time series S1, S2, especially the correlation coefficient.

    S1. S2
    0.029 2.470
    0.030 1.750
    0.030 2.200
    0.030 2.670
    0.031 2.130
    0.032 2.180
    0.030 3.410
    0.031 2.310
    0.032 2.170
    0.032 2.940
    0.032 2.580
    0.033 2.210
    0.034 2.110


    Three methods used return the same value, (i) method using spread sheet table, (ii) in built Numbers function correl and (iii) from scratch in spread sheet. These yield a value of -0.178 for xcorr at lag 0, the correlation coefficient.

    I have also written a short python code to do the

    import numpy as np
    import pandas as pn
    import pathlib
    home=pathlib.Path.home()
    filename = home/"Documents"/"Numcorr.csv"
    colnames = ["s1","s2"]
    df = pn.read_csv(filename,names = colnames, header = None)
    ts1 = df["s1"]
    ts2 = df["s2"]
    ts1 = (ts1-np.mean(ts1))/(np.std(ts1)*len(ts1))
    ts2 = (ts2-np.mean(ts2))/(np.std(ts2))
    corr = np.correlate(ts1,ts2,"full")
    opfile = home/"Documents"/"xcorr.csv"
    xcorr = np.flip(corr)
    print (xcorr)
    df3 = pn.DataFrame(xcorr)
    df3.to_csv(opfile, index = False)


    but occasionally numpy.correlate and numpy.corrcoef return incorrect values in comparison. In particular a value of -0.210.

    Any idea what is going wrong?

    Continue reading...

Compartilhe esta Página