我想建立一个具有日期时间x轴的函数/数组的数值推导。
我使用以下代码:
import numpy as np
import pandas as pd
df1 = pd.DataFrame({"x": ["1989-12-31 23:59:12", "1995-12-31 23:59:13", "2009-12-31 23:59:14"], "y": [1, 4, 9]})
df1["date"] = pd.to_datetime(df1.x)
df1.set_index("date", inplace=True)
df1.drop(["x"], axis=1, inplace=True)
并获得:
df1['derivation'] = np.gradient(df1.y, df1.index)
一个错误:
File "/home/user/anaconda3/lib/python3.6/site-packages/numpy/lib/function_base.py", line 1775, in gradient
a = -(dx2)/(dx1 * (dx1 + dx2))
TypeError: ufunc multiply cannot use operands with types dtype('<m8[ns]') and dtype('<m8[ns]')
并带有:
df1['derivation'] = np.gradient(df1.y, df1.index.to_pydatetime())
我得到:
File "/home/user/anaconda3/lib/python3.6/site-packages/numpy/lib/function_base.py", line 1775, in gradient
a = -(dx2)/(dx1 * (dx1 + dx2))
TypeError: unsupported operand type(s) for *: 'datetime.timedelta' and 'datetime.timedelta'
我必须如何提供非等距x轴作为np.gradient
的参数才能获得正确的结果?