我有一组日期时间对象,我想用 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'
除了手动转换日期时间对象之外,还有其他方法可以执行此操作吗?
最佳答案
.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)
关于python - Numpy 中的直方图日期时间对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30330389/