Xia*_*ang 10 python interpolation numpy pandas
我正在使用 numpy interp 来插入数据点,但得到 Cannot Cast array data from dtype('
代码片段:
import pandas as pd
import numpy as np
def interpolate_fwd_price(row, fx):
res = np.interp(row['SA_M'], fx['TENOR_DT'], fx['RATE'])
return res
df = pd.DataFrame({'SA_M': ['2018-02-28','2018-03-10']})
df['SA_M'] = pd.to_datetime(df['SA_M'])
data = pd.DataFrame({'TENOR_DT': ['2017-02-09','2017-03-02','2017-04-03','2017-05-02'], 'RATE':[1.0, 1.2, 1.5, 1.8]})
data['TENOR_DT'] = pd.to_datetime(data['TENOR_DT'])
df['PRICE'] = df.apply(interpolate_fwd_price, fx=data, axis=1)
Run Code Online (Sandbox Code Playgroud)
我做了一些搜索,但无法找出导致错误的原因。感谢您的意见。
进行一些更改,它可以用于插入日期时间差异而不是直接插入日期时间。仍然有兴趣知道为什么它不能直接插入日期时间。
def interpolate_fwd_price(row, fx):
fx['DT'] = (fx['TENOR_DT'] - row(['SA_M'])).dt.days
res = np.interp(0, fx['DT'], fx['RATE'])
return res
Run Code Online (Sandbox Code Playgroud)
In [92]: data = pd.DataFrame({'TENOR_DT': ['2017-02-09','2017-03-02','2017-04-03','2017-05-02'], 'RATE':[1.0, 1.2, 1.5, 1.8]})
In [93]: data # object dtype with strings
Out[93]:
RATE TENOR_DT
0 1.0 2017-02-09
1 1.2 2017-03-02
2 1.5 2017-04-03
3 1.8 2017-05-02
In [94]: data['TENOR_DT'] = pd.to_datetime(data['TENOR_DT'])
In [95]: data
Out[95]:
RATE TENOR_DT
0 1.0 2017-02-09
1 1.2 2017-03-02
2 1.5 2017-04-03
3 1.8 2017-05-02
In [96]: data['TENOR_DT']
Out[96]:
0 2017-02-09
1 2017-03-02
2 2017-04-03
3 2017-05-02
Name: TENOR_DT, dtype: datetime64[ns]
Run Code Online (Sandbox Code Playgroud)
日期的数组版本:
In [98]: dt = data['TENOR_DT'].values
In [99]: dt
Out[99]:
array(['2017-02-09T00:00:00.000000000', '2017-03-02T00:00:00.000000000',
'2017-04-03T00:00:00.000000000', '2017-05-02T00:00:00.000000000'],
dtype='datetime64[ns]')
Run Code Online (Sandbox Code Playgroud)
可以使用默认值将其转换为浮动unsafe:
In [100]: dt.astype(float)
Out[100]: array([1.4865984e+18, 1.4884128e+18, 1.4911776e+18, 1.4936832e+18])
In [101]: dt.astype(float, casting='safe')
TypeError: Cannot cast array from dtype('<M8[ns]') to dtype('float64') according to the rule 'safe'
Run Code Online (Sandbox Code Playgroud)
我的猜测是np.interp使用safe转换将这些日期时间值转换为浮点数。
我以前没有尝试过处理interp日期,所以只能建议一些修复。首先,您的日期仅因日而异,因此我们不需要完整的ns解决方案:
In [107]: dt.astype('datetime64[D]')
Out[107]:
array(['2017-02-09', '2017-03-02', '2017-04-03', '2017-05-02'],
dtype='datetime64[D]')
Run Code Online (Sandbox Code Playgroud)
它仍然不允许安全铸造,但“不安全”铸造会产生看起来合理的数字。您也许可以在插值中使用它们。
In [108]: dt.astype('datetime64[D]').astype(int)
Out[108]: array([17206, 17227, 17259, 17288])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27500 次 |
| 最近记录: |