根据规则“safe”,无法将数组数据从dtype('<M8[ns]')强制转换为dtype('float64')

2024-04-23 16:41:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用numpy interp插入数据点,但给定的数据点不能从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)

我做了一些搜索,但不知道是什么导致了这个错误。感谢你的意见。

进行一些更改,它可以用于插入日期时间差,而不是直接插入日期时间。仍然有兴趣知道为什么它不能直接插入日期时间。

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

Tags: dfdataratenpsadtresprice
1条回答
网友
1楼 · 发布于 2024-04-23 16:41:41
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]

日期的数组版本:

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]')

可以使用默认的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'

我的猜测是np.interp正在使用safe强制转换将这些日期时间值转换为浮点数。

我以前没有试过用日期,所以只能建议一些修复方法。首先,您的日期只因天而异,因此我们不需要完整的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]')

它仍然不允许安全浇铸,但“不安全”浇铸会产生看起来合理的数量。你可以在插值中使用这些。

In [108]: dt.astype('datetime64[D]').astype(int)
Out[108]: array([17206, 17227, 17259, 17288])

相关问题 更多 >