【问题标题】:How to get daily difference in time series values when time delta index is irregular in pandas?当熊猫的时间增量指数不规则时,如何获得时间序列值的每日差异?
【发布时间】:2020-05-26 19:35:13
【问题描述】:

我有一个数据框,其中包含按时间索引的时间序列,但时间增量不规则,如下所示

df
time                  x
2018-08-18 17:45:08   1.4562
2018-08-18 17:46:55   1.4901
2018-08-18 17:51:21   1.8012
...
2020-03-21 04:17:19   0.7623
2020-03-21 05:01:02   0.8231
2020-03-21 05:02:34   0.8038

我想要做的是获得两个(按时间顺序)最接近的值之间的每日差异,即第二天最接近的时间。例如,如果我们在 2018 年 8 月 18 日 17:45:08 有一个样本,而第二天我们同时没有样本,但最接近的样本是在 2018 年 8 月 19 日17:44:29,然后我想得到这两次之间x的差异。在 pandas 中怎么可能?

  • 在时间序列的第一天和最后一天之间的每一天都会有一个样本。
  • 差值应视为(当前 x)-(过去 x),例如x_day2 - x_day1
  • 输出的第一行 n 将是 NaN 考虑到差异是如何产生的,其中 n 是第一天的样本数

编辑:如果时间增量是规则的,下面的代码可以工作

def get_daily_diff(data):
    """
    Calculate daily difference in time series

    Args:
        data (pandas.Series): a pandas series of time series values indexed by pandas.Timestamp

    Returns:
        pandas.Series: daily difference in values
    """
    df0 = data.index.searchsorted(data.index - pd.Timedelta(days=1))
    df0 = df0[df0 > 0]
    df0 = pd.Series(data.index[df0 - 1], index=data.index[data.shape[0] - df0.shape[0]:])
    out = data.loc[df0.index] - data.loc[df0.values]
    return out

但是,如果使用不规则的时间延迟,则在定义变量 out 时会抛出 ValueError,因为我们得到 data.loc[df0.index]data.loc[df0.values] 之间的长度不匹配。所以问题是在时间增量不规则的情况下扩展此功能。

【问题讨论】:

  • 您能否提供您的代码https://stackoverflow.com/help/minimal-reproducible-example 的最小可重现示例,以便其他用户可以重现您的问题?谢谢!
  • 好问题。预期的输出是多少?您想为数据中的每一行获取最近的明天吗?最后一天的预期产出是多少?
  • @Roy2012 是明天最接近的时间,感谢您的提问。我对问题进行了编辑

标签: python pandas time-series


【解决方案1】:

我会将pd.merge_asofdirection='nearest' 一起使用:

df['time_1d'] = df['time']+pd.Timedelta('1D')
tmp = pd.merge_asof(df, df, left_on='time', right_on ='time_1d',
           direction='nearest', tolerance=pd.Timedelta('12H'), suffixes=('', '_y'))
tmp['delta'] = tmp['x_y'] - tmp['x']
tmp = tmp[['time', 'x', 'delta']]

这里我使用了 12H 的容差来确保第一天有 NaN,但您可以使用更合适的值。

【讨论】:

  • 这看起来真的很接近,但我们想采取差异x_day2 - x_day1,所以实际上输出中的第一个 n天是NaN - 抱歉困惑,我编辑了这个问题来解释这一点。我们如何修改您的解决方案来做到这一点?
  • @PyRsquared 只需在合并中切换时间列即可。在我上次的编辑中已经完成。
猜你喜欢
  • 1970-01-01
  • 2014-02-05
  • 2013-10-09
  • 1970-01-01
  • 1970-01-01
  • 2020-05-31
  • 2017-11-17
  • 2014-06-02
  • 2013-06-05
相关资源
最近更新 更多