【发布时间】: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