创建过期的numpy linspace
我正在编写一个脚本,该脚本在x轴上绘制一些带有日期的数据(在matplotlib中)。我需要numpy.linspace
从这些日期中创建一个,以便随后创建一个样条线。有可能这样做吗?
我尝试过的
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')
-
您考虑过使用
pandas
吗?使用这个可能重复的问题中的一种方法,您可以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]')