mar*_*tin 5 python datetime numpy histogram
我有一个datetime对象数组,我想用Python直方图.
Numpy 直方图方法不接受日期时间,抛出的错误是
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'
Run Code Online (Sandbox Code Playgroud)
除了手动转换datetime对象之外,还有其他方法可以执行此操作吗?
该.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)
Run Code Online (Sandbox Code Playgroud)
numpy.histogram仅适用于数字。当dt_array你的数组datetime对象,这将给你直方图:
to_timestamp = np.vectorize(lambda x: x.timestamp())
time_stamps = to_timestamp(dt_array)
np.histogram(time_stamps)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4194 次 |
| 最近记录: |