我正在编写一个脚本,在x轴上绘制一些带有日期的数据(在matplotlib中)。我需要在这些日期之外创建一个numpy.linspace
,以便在以后创建一个spline。有可能做到这一点吗?
我尝试过的:
import datetime
import numpy as np
dates = [
datetime.datetime(2015, 7, 2, 0, 31, 41),
datetime.datetime(2015, 7, 2, 1, 35),
datetime.datetime(2015, 7, 2, 2, 37, 9),
datetime.datetime(2015, 7, 2, 3, 59, 16),
datetime.datetime(2015, 7, 2, 5, 2, 23)
]
x = np.linspace(min(dates), max(dates), 500)
它抛出这个错误:
TypeError: unsupported operand type(s) for *: 'datetime.datetime' and 'float'
我也尝试过将datetime
转换为np.datetime64
,但效果不佳:
dates = [np.datetime64(i) for i in dates]
x = np.linspace(min(dates), max(dates), 500)
错误:
TypeError: ufunc multiply cannot use operands with types dtype('<M8[us]') and dtype('float64')
发布于 2016-06-22 18:04:59
您是否考虑过使用pandas
?通过使用this possible duplicate question中的方法,您可以通过以下方式使用np.linspace
import pandas as pd
start = pd.Timestamp('2015-07-01')
end = pd.Timestamp('2015-08-01')
t = np.linspace(start.value, end.value, 100)
t = pd.to_datetime(t)
获取线性时间序列的np.array
In [3]: np.asarray(t)
Out[3]:
array(['2015-06-30T17:00:00.000000000-0700',
'2015-07-01T00:30:54.545454592-0700',
'2015-07-01T08:01:49.090909184-0700',
...
'2015-07-31T01:58:10.909090816-0700',
'2015-07-31T09:29:05.454545408-0700',
'2015-07-31T17:00:00.000000000-0700'], dtype='datetime64[ns]')
发布于 2018-06-06 20:02:00
从pandas 0.23开始,您可以使用date
import pandas as pd
x = pd.date_range(min(dates), max(dates), periods=500).to_pydatetime()
发布于 2016-06-22 11:06:07
据我所知,np.linspace不支持datetime对象。但也许我们可以制作自己的函数来粗略地模拟它:
def date_linspace(start, end, steps):
delta = (end - start) / steps
increments = range(0, steps) * np.array([delta]*steps)
return start + increments
这应该会给你一个在steps
步骤中从start
到end
的日期的np.array (不包括结束日期,可以很容易地修改)。
https://stackoverflow.com/questions/37964100
复制