使两个采样率不同的时间序列具有可比性

2024-06-09 02:32:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两组数据,都是随时间变化的时间序列(在这两种情况下都是相同的),我使用pandas和matplotlib导入并绘制了它们

from os import chdir
chdir('C:\\Users\\me\\Documents\\Folder')

# import necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# read in csv file
file_df = pd.read_csv('C://Users//me//Documents//Folder//file.csv')

# define csv columns and assign values
VarA = file_df.loc[:, 'VarA'].values
TimeA = file_df.loc[:, 'TimeA'].values
VarB = file_df.loc[:, 'VarB'].values
TimeB = file_df.loc[:, 'TimeB'].values


# plot data selection and aesthetics
plt.plot(TimeA, VarA)
plt.plot(TimeB, VarB)

# plot labels
plt.xlabel('Time')
plt.ylabel('Variable')

#plot and add legend based on plot labels
plt.legend()

在这两种情况下,变量在0分钟到320分钟之间采样。但是,一个数据集有775个样本(在320分钟内以随机间隔采集),另一个数据集有1732个样本(同样,在320分钟内以随机间隔采集)

基本上,我想做的是在旧数据集的基础上创建两个新的数据集,其中变量与时间的关系在0到320分钟之间,但这两个数据集的变量A的数据点数量相同,且在相同的时间步长上进行(例如,对于320个样本,每分钟的变量)

我猜需要一些插值?我真的不知道从哪里开始。我在同一个.csv中有两个数据集,我需要它们具有相同的样本大小,以便我可以运行以下计算。目前它没有运行,因为“VarA”和“VarB”的数据量不同

x_values = VarB
y_values = VarA

correlation_matrix = np.corrcoef(x_values, y_values)
correlation_xy = correlation_matrix[0,1]
r_squared = correlation_xy**2

Tags: csv数据importdfplotas时间plt
2条回答

有很多方法可以解决这个问题。通过计算随时间变化的两个变量之间的相关性,您试图解决的问题是什么

一种选择是计算一段时间内的某种加权移动平均数,然后以这种方式进行相关性计算。最简单的方法是指数加权移动平均,如loess函数。还有更复杂的方法

下面是一些示例代码,我取了一个余弦函数和一个加了随机噪声的函数。要进行黄土拟合,请使用leuch()函数,并访问要由lowess返回值的“fitted”变量的拟合值

x = seq(from = 1, to = 100)
y1 = cos(x / 10)
y2 = cos(x / 10) + rnorm(100, mean = 0, sd = 0.25)

smooth_y2 = loess(y2 ~ x)
plot(x, y1, type = 'l')
lines(x, smooth_y2$fitted, type = 'l', col = 'red')
print(cor(y1, smooth_y2$fitted))

我认为resample在这里可能有用

相关问题 更多 >