python中缺少时间序列值

2024-05-20 16:06:30 发布

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

我有一个时间序列数据帧,数据帧很大,在2列中包含一些缺少的值(“湿度”和“压力”)。我想用一种巧妙的方法来估算这个缺失的值,例如使用最近邻居的值或上一个和下一个时间戳的平均值。有没有一种简单的方法可以做到这一点?我试过使用fancyicompute,但数据集包含大约180000个示例,并给出了一个内存错误enter image description here


Tags: 数据方法内存示例错误时间序列平均值
3条回答

你可以这样使用rolling

frame = pd.DataFrame({'Humidity':np.arange(50,64)})

frame.loc[[3,7,10,11],'Humidity'] = np.nan

frame.Humidity.fillna(frame.Humidity.rolling(4,min_periods=1).mean())

输出:

0     50.0
1     51.0
2     52.0
3     51.0
4     54.0
5     55.0
6     56.0
7     55.0
8     58.0
9     59.0
10    58.5
11    58.5
12    62.0
13    63.0
Name: Humidity, dtype: float64

插值和滤波:

由于是时间序列问题,我将在答案中使用o/p图图像进行解释:

假设我们有如下时间序列的数据:(在x轴上=天数,y=数量)

pdDataFrame.set_index('Dates')['QUANTITY'].plot(figsize = (16,6))

enter image description here

我们可以看到时间序列中有一些NaN数据。%nan=19.400%的总数据。现在我们要估算null/nan值。

我将尝试向您显示插值和filna方法的o/p,以在数据中填充Nan值。

插值():

首先我们将使用插值:

pdDataFrame.set_index('Dates')['QUANTITY'].interpolate(method='linear').plot(figsize = (16,6))

enter image description here

注:这里没有时间插值法

使用回填方法填充

pdDataFrame.set_index('Dates')['QUANTITY'].fillna(value=None, method='backfill', axis=None, limit=None, downcast=None).plot(figsize = (16,6))

enter image description here

使用回填方法fillna()&limit=7

限制:这是要向前/向后填充的最大连续NaN值数。换言之,如果连续的nan数量超过此数量,则只会部分填补空缺。

pdDataFrame.set_index('Dates')['QUANTITY'].fillna(value=None, method='backfill', axis=None, limit=7, downcast=None).plot(figsize = (16,6))

enter image description here

我发现fillna函数更有用。但是您可以使用任何一种方法来填充两列中的nan值。

有关这些功能的详细信息,请参阅以下链接:

  1. 菲娜:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.fillna.html#pandas.Series.fillna
  2. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.interpolate.html

还有一个库可以签出。有关此库的详细信息,请参阅此链接:https://pypi.org/project/impyute/

考虑一下interpolatedocumentation)。此示例演示如何用直线填充任何大小的间隙:

df = pd.DataFrame({'date': pd.date_range(start='2013-01-01', periods=10, freq='H'), 'value': range(10)})
df.loc[2:3, 'value'] = np.nan
df.loc[6, 'value'] = np.nan
df
                 date  value
0 2013-01-01 00:00:00    0.0
1 2013-01-01 01:00:00    1.0
2 2013-01-01 02:00:00    NaN
3 2013-01-01 03:00:00    NaN
4 2013-01-01 04:00:00    4.0
5 2013-01-01 05:00:00    5.0
6 2013-01-01 06:00:00    NaN
7 2013-01-01 07:00:00    7.0
8 2013-01-01 08:00:00    8.0
9 2013-01-01 09:00:00    9.0

df['value'].interpolate(method='linear', inplace=True)
                 date  value
0 2013-01-01 00:00:00    0.0
1 2013-01-01 01:00:00    1.0
2 2013-01-01 02:00:00    2.0
3 2013-01-01 03:00:00    3.0
4 2013-01-01 04:00:00    4.0
5 2013-01-01 05:00:00    5.0
6 2013-01-01 06:00:00    6.0
7 2013-01-01 07:00:00    7.0
8 2013-01-01 08:00:00    8.0
9 2013-01-01 09:00:00    9.0

相关问题 更多 >