【问题标题】:List comprehension with pandas datetime index使用 pandas 日期时间索引的列表理解
【发布时间】:2013-07-27 04:19:01
【问题描述】:

我正在使用 datetime 索引在 pandas 数据帧中寻找 6 小时的间隔,我想使用类似这样的列表理解在间隔之后创建一个包含 datetime 对象的列表:

starttimes = [x for i, x in enumerate(data.index) if ((x - x[i-1]).seconds/3600.0) > 6 ]

但我收到以下类型错误:

TypeError: 'Timestamp' object does not support indexing

错误发生在 enumerate(data.index) 之后,但我不确定为什么会收到此错误,因为我可以这样做:

(data.index[0] - data.index[1]).seconds/3600.0 > 6

很好,输出为真。

我也尝试过这种方式,但得到了不同类型的错误:

starttime = [x for i, x in enumerate(WaterTest) if ((x.index - x.index[i-1]).seconds/3600.0) > 6 ]

TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'

有没有办法轻松做到这一点?我必须在我的代码中经常使用这样的语句,如果能够以类似的方式编写它们会很好。

【问题讨论】:

    标签: python datetime pandas list-comprehension typeerror


    【解决方案1】:

    在迭代时,DatetimeIndex 将其值转换为时间戳

    In [26]: index = pd.DatetimeIndex(['20130101 12:00:00','20130101 18:01:01','20130102 9:00:00','20130102 23:00:05'])
    
    In [27]: index
    Out[27]: 
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2013-01-01 12:00:00, ..., 2013-01-02 23:00:05]
    Length: 4, Freq: None, Timezone: None
    
    In [28]: for x in index:
       ....:     print type(x)
       ....:     
    <class 'pandas.tslib.Timestamp'>
    <class 'pandas.tslib.Timestamp'>
    <class 'pandas.tslib.Timestamp'>
    <class 'pandas.tslib.Timestamp'>
    

    但是有一个更简单的方法来做你正在做的事情

    时间 - shift_time = timedelta

    In [29]: td = index.to_series().diff()
    
    In [30]: td
    Out[30]: 
    2013-01-01 12:00:00        NaT
    2013-01-01 18:01:01   06:01:01
    2013-01-02 09:00:00   14:58:59
    2013-01-02 23:00:05   14:00:05
    dtype: timedelta64[ns]
    

    这在 numpy >= 1.7 中有效(请参阅此处了解您可以执行的其他操作以及如果 numpy http://pandas.pydata.org/pandas-docs/dev/timeseries.html#time-deltas

    以 6 小时为单位的差异

    In [31]: td.apply(lambda x: x/np.timedelta64(6,'h'))
    Out[31]: 
    2013-01-01 12:00:00         NaN
    2013-01-01 18:01:01    1.002824
    2013-01-02 09:00:00    2.497176
    2013-01-02 23:00:05    2.333565
    dtype: float64
    

    【讨论】:

    • 我的 numpy 版本是 1.7.1,但我不能像上面那样在 td 上使用 .diff() 或 .apply 我需要获取更新的版本吗?
    • 忘记导入日期时间,但它现在可以工作而且速度很快!谢谢
    猜你喜欢
    • 1970-01-01
    • 2017-10-18
    • 2018-05-15
    • 2015-07-02
    • 2012-10-16
    • 1970-01-01
    • 2015-02-21
    • 2017-04-15
    • 2012-08-24
    相关资源
    最近更新 更多