Python 使用scipy.signal中的nan值去趋势化数据
我有一个包含一些nan值的时间序列数据集。我要删除此数据: 我试着这样做:Python 使用scipy.signal中的nan值去趋势化数据,python,numpy,scipy,trend,Python,Numpy,Scipy,Trend,我有一个包含一些nan值的时间序列数据集。我要删除此数据: 我试着这样做: scipy.signal.detrend(y) 然后我得到了这个错误: ValueError: array must not contain infs or NaNs 然后我试着: scipy.signal.detrend(y.dropna()) 但我丢失了数据顺序 如何解决这个问题?有一个数字信号处理堆栈站点供将来参考。我建议将来在与信号处理相关的问题上使用它 我能想到的最简单的方法是手动删除数据。通过计算最小
scipy.signal.detrend(y)
然后我得到了这个错误:
ValueError: array must not contain infs or NaNs
然后我试着:
scipy.signal.detrend(y.dropna())
但我丢失了数据顺序
如何解决这个问题?有一个数字信号处理堆栈站点供将来参考。我建议将来在与信号处理相关的问题上使用它
我能想到的最简单的方法是手动删除数据。通过计算最小二乘法,您可以很容易地做到这一点。最小二乘法将同时考虑
x
和y
值,因此您可以删除与y=NaN
对应的x
值
您可以使用not\u NaN\u ind=~np.isnan(y)
获取非NaN
值的索引,然后使用y
的非NaN
值和相应的x
值进行线性回归,例如:
然后,您只需从数据y
中减去该行即可获得去渲染数据:
detrend_y = y - (m*x + b)
这就是你所需要的。例如,对于一些虚拟数据:
import numpy as np
from matplotlib import pyplot as plt
from scipy import stats
# create data
x = np.linspace(0, 2*np.pi, 500)
y = np.random.normal(0.3*x, np.random.rand(len(x)))
drops = np.random.rand(len(x))
y[drops>.95] = np.NaN # add some random NaNs into y
plt.plot(x, y)
仅删除非nan零件,但保留nan零件:
signal[np.logical_not(pd.isna(signal))] = scipy.signal.detrend(signal[np.logical_not(pd.isna(signal))])
您可以将
NaN
值设置为其附近值的平均值。您的另一个主要方法是手动删除数据;i、 例如,对已有的数据使用线性最小二乘法,然后减去该行。不太难。这里有一系列函数:scipy.linalg.lstsq
,scipy.stats.linregresse
,scipy.optimize.least\u squares
,scipy.optimize.lsq\u linear
,numpy.linaleg.lssq
@AlexanderReynolds是的。插值对我没有帮助,所以从数据中减去直线可能会有所帮助。谢谢您对这个过程的详细解释。有帮助:)
# find linear regression line, subtract off data to detrend
not_nan_ind = ~np.isnan(y)
m, b, r_val, p_val, std_err = stats.linregress(x[not_nan_ind],y[not_nan_ind])
detrend_y = y - (m*x + b)
plt.plot(x, detrend_y)
signal[np.logical_not(pd.isna(signal))] = scipy.signal.detrend(signal[np.logical_not(pd.isna(signal))])