TypeError: cannot astype a datetimelike from [datetime64[ns]] to [int32]
时间: 2023-09-30 16:07:34 浏览: 78
`TypeError: cannot astype a datetimelike from [datetime64[ns]] to [int32]` 这个错误通常是由于 Pandas 的版本问题导致的。在较旧的 Pandas 版本中,`astype(int)` 方法可以将时间类型转换为整数类型的时间戳,但是在新版本中则会报错。
解决该错误的方法是,使用 Pandas 的 `astype` 方法将时间类型转换为 `int64` 类型,然后再将其转换为整数类型的时间戳。具体来说,你可以使用以下代码:
```python
import torch
import pandas as pd
# 获取时间列
time_col = data.iloc[:, 0]
# 转换为标准时间戳字符串
time_format = '%Y-%m-%d %H:%M:%S.%f'
time_series = time_col.apply(lambda x: pd.to_datetime(x, format=time_format))
# 转换为浮点数张量
time_tensor = torch.tensor(time_series.astype('int64').values / 1e9, dtype=torch.float32)
# 将时间张量转换为原始形状
time_tensor = time_tensor.view(data.shape[0], data.shape[1], 1)
```
其中,`time_series.astype('int64')` 将时间类型转换为 `int64` 类型,然后使用 `.values` 将其转换为 Numpy 数组,并将其除以 `1e9` 转换为以秒为单位的浮点数。最后,你可以将其转换为浮点数张量,并使用 `view` 方法将其转换为原始形状。
需要注意的是,这里假设时间列的格式为 `%Y-%m-%d %H:%M:%S.%f`,如果时间列的格式不同,需要根据实际情况进行调整。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)