【问题标题】:Filtering negative timedeltas过滤负时间增量
【发布时间】:2016-04-20 00:55:52
【问题描述】:

考虑一个持有timedelta64[ns] 的系列,它测量两个事件 A 和 B 之间的时间差:

> time_deltas

499900   -1 days +23:45:13
499916   -1 days +23:50:57
499917            00:03:27
499919            00:17:45
499920            00:16:56
499921   -1 days +23:59:26
499922            00:16:34
499923            00:15:46
499928            00:12:56
499929            00:05:54
                ...       
499970            00:00:48
499971   -1 days +23:58:32

dtype: timedelta64[ns]

如何识别负增量? (例如 A 发生在 B 之前)。

这不起作用:

> time_deltas[time_deltas<0]
TypeError: invalid type comparison

还要考虑以下几点:

# Negative  time delta example:
> time_deltas.iloc[-1]
Timedelta('-1 days +23:58:32')

# Values seem to have integer representation in ns
> time_deltas.iloc[-1].value
-88000000000

# Positive time delta example:
> time_deltas.iloc[-2]
Timedelta('0 days 00:00:48')

# Again, values seem to have integer representation in ns
> time_deltas.iloc[-1].value
48000000000

然后:

# Trying to use the internal representation fails
> time_deltas.apply(lambda x: x.value>0)
AttributeError: 'numpy.timedelta64' object has no attribute 'value'

# Same with
> time_deltas.apply(lambda x: x['value']>0)
IndexError: invalid index to scalar variable.

【问题讨论】:

    标签: python pandas time-series


    【解决方案1】:

    pd.Timedelta(0)比较:

    In [60]: time_deltas = pd.to_timedelta(np.random.randint(-10**6, 10**6, size=10))
    
    In [61]: time_deltas
    Out[61]: 
    TimedeltaIndex([         '00:00:00.000809', '-1 days +23:59:59.999034',
                    '-1 days +23:59:59.999456', '-1 days +23:59:59.999156',
                    '-1 days +23:59:59.999053', '-1 days +23:59:59.999723',
                    '-1 days +23:59:59.999523',          '00:00:00.000349',
                             '00:00:00.000051',          '00:00:00.000774'],
                   dtype='timedelta64[ns]', freq=None)
    
    In [62]: time_deltas < pd.Timedelta(0)
    Out[62]: array([False,  True,  True,  True,  True,  True,  True, False, False, False], dtype=bool)
    

    【讨论】:

      猜你喜欢
      • 2015-12-19
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多