【问题标题】:Histogram datetime objects in NumpyNumpy中的直方图日期时间对象
【发布时间】:2015-07-31 13:29:52
【问题描述】:

我有一组日期时间对象,我想在 Python 中对它们进行直方图。

Numpy histogram 方法不接受日期时间,抛出的错误是

File "/usr/lib/python2.7/dist-packages/numpy/lib/function_base.py", line 176, in histogram
mn, mx = [mi+0.0 for mi in range]
TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'float'

除了手动转换日期时间对象之外,还有其他方法吗?

【问题讨论】:

    标签: python datetime numpy histogram


    【解决方案1】:

    .timestamp() 方法似乎只适用于Python 3.3。如果您使用的是旧版本的 Python,则需要直接计算:

    import datetime
    import numpy as np
    
    to_timestamp = np.vectorize(lambda x: (x - datetime.datetime(1970, 1, 1)).total_seconds())
    from_timestamp = np.vectorize(lambda x: datetime.datetime.utcfromtimestamp(x))
    
    ## Compute the histogram
    hist, bin_edges = np.histogram(to_timestamp(dates))
    
    ## Print the histogram, and convert bin edges back to datetime objects
    print hist, from_timestamp(bin_edges)
    

    【讨论】:

    • 你也可以这样做:np.vectorize(lambda x: int(x.strftime('%s'))
    • 为什么要从1970年开始? (即to_timestamp = np.vectorize(lambda x: (x - datetime.datetime(1970, 1, 1)).total_seconds())
    • 看起来:to_timestamp = np.vectorize(lambda x: (x - datetime.datetime(1, 1, 1)).total_seconds()) from_timestamp = np.vectorize(lambda x: (datetime.datetime(1, 1, 1) + datetime.timedelta(seconds=x)) ) 会更通用(处理从第 1 年开始的日期)
    【解决方案2】:

    numpy.histogram 仅适用于数字。当dt_array 是您的datetime 对象数组时,这将为您提供直方图:

    to_timestamp = np.vectorize(lambda x: x.timestamp())
    time_stamps = to_timestamp(dt_array)
    np.histogram(time_stamps)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-12
      • 2017-04-12
      • 1970-01-01
      • 1970-01-01
      • 2014-07-17
      • 1970-01-01
      • 2016-04-28
      相关资源
      最近更新 更多