我有一个数据帧,其中包含一个按时间索引的时间序列,但具有不规则的时间增量,如下所示
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,那么我想得到这两个时间之间的差值。这在熊猫身上怎么可能
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]
之间存在长度不匹配。因此,问题是将此函数扩展到在时间增量不规则的情况下工作
我将
pd.merge_asof
与direction='nearest'
一起使用:在这里,我使用了12小时的公差来确保第一天有NaN,但您可以使用更合适的值
相关问题 更多 >
编程相关推荐