如何去除两个变量之间的线性拟合?

How to remove linear fit between two variables?

我想通过移除两个变量 X 和 Y 之间的拟合线来移除它们之间的相关性。我的土码如下:

X = pd.read_csv (r'C:\Users\folder\X.csv') 
X = pd.DataFrame(X,columns=['Year','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'])
X  X[X['Year'].between(1984,2020, inclusive="both")]

Y = pd.read_csv (r'C:\Users\folder\Y.csv') 
Y = pd.DataFrame(Y,columns=['Year','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'])
Y=Y[Y['Year'].between(1984,2020, inclusive="both")]
    

我想通过移除 X 的相关性将 Y 转换为 new_Y。我只对移除 'Mar' 中的相关性感兴趣。我正在使用 jupyter notebook,我对 python 或任何其他编程语言都很陌生。提前致谢。

This is the data. I used 1984-2020 only when I read the .csv

不幸的是,您添加数据的方式不是很有帮助,因为我无法复制和粘贴它。但是,我认为这是一个您可以概括的示例。如果您有任何问题,请告诉我。

相关向量 y 是使用 this link 中概述的方法创建的。

import numpy as np

# Generate two random vectors
x1 = np.random.rand(100)
x2 = np.random.rand(100)

# Generate another vector, linearly correlated with x1
corr_coef = 0.7
y = corr_coef * x1 + np.sqrt(1 - corr_coef ** 2) * x2 

p = np.polyfit(x1, y, 1)

# Remove the correlation with x1 by subracting the linear fit:
uncorr_y = y - np.polyval(p, x1)

# plot the original data with the fit
plt.figure()
plt.plot(x1, y,'.')
plt.plot(x1, np.polyval(p, x1), 'r-')
plt.xlabel('x1')
plt.ylabel('y')
plt.show()

# Plot the uncorrelated data
plt.figure()
plt.plot(x1, uncorr_y ,'.')
plt.xlabel('x1')
plt.ylabel(r'$y_{uncorr}$')
plt.show()

这是相关和不相关数据的图表: