当Pandas的时间增量指数不规则时,如何获得时间序列值的日差?

2024-07-03 02:39:58 发布

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

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

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-08-18 17:45:08有一个样本,而第二天我们在同一时间没有样本,但最接近的样本是,比如2018-08-19 17:44:29,那么我想得到这两个时间之间的差值。这在熊猫身上怎么可能

  • 在时间序列的第一天和最后一天之间的每一天都会有一个样本
  • 差值应视为(当前x)-(过去x),例如x_第2天-x_第1天
  • 根据差异的计算方式,输出的第一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]之间存在长度不匹配。因此,问题是将此函数扩展到在时间增量不规则的情况下工作


Tags: pandasdataindextime时间out增量loc
1条回答
网友
1楼 · 发布于 2024-07-03 02:39:58

我将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']]

在这里,我使用了12小时的公差来确保第一天有NaN,但您可以使用更合适的值

相关问题 更多 >