微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

类型错误:不能将日期时间类型从 [datetime64[ns]] 到 [int32]请说明解决此问题的程序

如何解决类型错误:不能将日期时间类型从 [datetime64[ns]] 到 [int32]请说明解决此问题的程序

我正在使用机器学习算法交易一书中的代码重建股票交易订单簿。 我运行以下 Python 代码

buy_per_min = (buy
           .groupby([pd.Grouper(key='timestamp',freq='Min'),'price'])
           .shares
           .sum()
           .apply(np.log)
           .to_frame('shares')
           .reset_index('price')
           .between_time(market_open,market_close)
           .groupby(level='timestamp',as_index=False,group_keys=False)
           .apply(lambda x: x.nlargest(columns='price',n=depth))
           .reset_index())
buy_per_min.timestamp = buy_per_min.timestamp.add(utc_offset).astype(int)
buy_per_min.info()

代码运行时,我得到以下错误语句。我使用的是 Windows 10,我的代码编辑器是带有 Jupyter Notebok 扩展的 MS Virtual Studio Code。我之前执行的所有代码都运行良好。任何建议将不胜感激。

TypeError: cannot astype a datetimelike from [datetime64[ns]] to [int32]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-26-396768b710c8> in <module>
     10                .apply(lambda x: x.nlargest(columns='price',n=depth))
     11                .reset_index())
---> 12 buy_per_min.timestamp = buy_per_min.timestamp.add(utc_offset).astype(int)
     13 buy_per_min.info()

~\anaconda3\lib\site-packages\pandas\core\generic.py in astype(self,dtype,copy,errors)
   5875         else:
   5876             # else,only a single dtype is given
-> 5877             new_data = self._mgr.astype(dtype=dtype,copy=copy,errors=errors)
   5878             return self._constructor(new_data).__finalize__(self,method="astype")
   5879 

~\anaconda3\lib\site-packages\pandas\core\internals\managers.py in astype(self,errors)
    629         self,copy: bool = False,errors: str = "raise"
    630     ) -> "BlockManager":
--> 631         return self.apply("astype",dtype=dtype,errors=errors)
    632 
    633     def convert(

~\anaconda3\lib\site-packages\pandas\core\internals\managers.py in apply(self,f,align_keys,ignore_failures,**kwargs)
    425                     applied = b.apply(f,**kwargs)
    426                 else:
--> 427                     applied = getattr(b,f)(**kwargs)
    428             except (TypeError,NotImplementedError):
    429                 if not ignore_failures:

~\anaconda3\lib\site-packages\pandas\core\internals\blocks.py in astype(self,errors)
   2280 
   2281         # delegate
-> 2282         return super().astype(dtype=dtype,errors=errors)
   2283 
   2284     def _can_hold_element(self,element: Any) -> bool:

~\anaconda3\lib\site-packages\pandas\core\internals\blocks.py in astype(self,errors)
    671             vals1d = values.ravel()
    672             try:
--> 673                 values = astype_nansafe(vals1d,copy=True)
    674             except (ValueError,TypeError):
    675                 # e.g. astype_nansafe can fail on object-dtype of strings

~\anaconda3\lib\site-packages\pandas\core\dtypes\cast.py in astype_nansafe(arr,skipna)
   1039             return arr.astype(dtype)
   1040 
-> 1041         raise TypeError(f"cannot astype a datetimelike from [{arr.dtype}] to [{dtype}]")
   1042 
   1043     elif is_timedelta64_dtype(arr):

TypeError: cannot astype a datetimelike from [datetime64[ns]] to [int32] 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。