Pandas 熊猫时间序列:满足特定条件的总持续时间

Pandas 熊猫时间序列:满足特定条件的总持续时间,pandas,Pandas,我有一个时间表 ts = pd.Series(data=[0,1,2,3,4],index=[pd.Timestamp('1991-01-01'),pd.Timestamp('1995-01-01'),pd.Timestamp('1996-01-01'),pd.Timestamp('2010-01-01'),pd.Timestamp('2011-01-01')]) 假设值在下一个时间步指示之前有效(无线性插值),获取值小于2的总持续时间的最快、最可读的方法是什么。我想可能有一个pandas函数

我有一个时间表

ts = pd.Series(data=[0,1,2,3,4],index=[pd.Timestamp('1991-01-01'),pd.Timestamp('1995-01-01'),pd.Timestamp('1996-01-01'),pd.Timestamp('2010-01-01'),pd.Timestamp('2011-01-01')])

假设值在下一个时间步指示之前有效(无线性插值),获取值小于2的总持续时间的最快、最可读的方法是什么。我想可能有一个pandas函数用于此

这似乎工作得很好,但我仍然感到困惑的是,似乎没有一个pandas函数用于此

import pandas as pd
import numpy as np

ts = pd.Series(data=[0,1,2,3,4],index=[pd.Timestamp('1991-01-01'),pd.Timestamp('1995-01-01'),pd.Timestamp('1996-01-01'),pd.Timestamp('2010-01-01'),pd.Timestamp('2011-01-01')])

# making the timeseries binary. 1 = meets condition, 0 = does not
ts = ts.where(ts>=2,other=1)
ts = ts.where(ts<2,other=0)

delta_time = ts.index.to_pydatetime()[1:]-ts.index.to_pydatetime()[:-1]

time_below_2 = np.sum(delta_time[np.invert(ts.values[:-1])]).total_seconds()
time_above_2 = np.sum(delta_time[(ts.values[:-1])]).total_seconds()
将熊猫作为pd导入
将numpy作为np导入
ts=pd.系列(数据=[0,1,2,3,4],索引=[pd.时间戳('1991-01-01')、pd.时间戳('1995-01-01')、pd.时间戳('1996-01-01')、pd.时间戳('2010-01-01')、pd.时间戳('2011-01-01'))
#使时间序列成为二进制。1=符合条件,0=不符合条件
ts=ts,其中(ts>=2,其他=1)
ts=ts,其中(ts=value,其他=1)
ts=ts,其中(ts
这是否有被否决的原因?为了将来的参考,我想解释一下这里出了什么问题:)
def get_total_duration_above_and_below_value(value,ts):

    # making the timeseries binary. 1 = above value, 0 = below value
    ts = ts.where(ts >= value, other=1)
    ts = ts.where(ts < value, other=0)

    time_above_value = 0
    time_below_value = 0
    for i in range(ts.size - 1):
        if ts[i] == 1:
            time_above_value += abs(pd.Timedelta(
                ts.index[i] - ts.index[i + 1]).total_seconds()) / 3600
        else:
            time_below_value += abs(pd.Timedelta(
                ts.index[i] - ts.index[i + 1]).total_seconds()) / 3600

    return time_above_value, time_below_value