Skip to main content
 首页 » 编程设计

python之散点图和线性回归的日期问题

2025年05月04日15qq号

我有两个问题,我相信它们都以日期格式发布。

我有一份包含日期和值的简历:

2012-01-03 00:00:00     95812     
2012-01-04 00:00:00    101265  
...  
2016-10-21 00:00:00     93594 

在我用 read_csv 加载它之后,我试图用以下方法解析日期:

X.Dated = pd.to_datetime(X.Dated, format='%Y-%m-%d %H:%M:%S', errors='raise') 

我也尝试过:

dateparse = lambda x: pd.datetime.strptime(x, '%Y-%m-%d %H:%M:%S') 
X = pd.read_csv('sales.csv', parse_dates=['Dated'], date_parser=dateparse) 

和infer_datetime_format参数。

所有这些似乎都工作正常,因为当我打印出来时日期看起来像:2012-01-03。

当我试图在图表上绘制数据时出现问题,这一行:

ax.scatter(X.Dated, X.Val, c='green', marker='.') 

给我一​​个错误:

TypeError: invalid type promotion 

此外,当我尝试将它与 LinearRegression() 算法一起使用时,拟合命令 工作正常但分数和预测给了我这个错误:

TypeError: Cannot cast array data from dtype('<M8[ns]') to dtype('float64') according to the rule 'safe' 

我尝试了很多方法来修复它,但没有成功。 任何帮助,将不胜感激。

请您参考如下方法:

ax.scatter(目前)不接受 Pandas 系列,但它可以接受 Pandas 时间戳列表(例如 X['Dated'].tolist()),或 dtype datetime64[ns] 的 NumPy 数组(例如 X['Dated'].values):

import pandas as pd 
import matplotlib.pyplot as plt 
 
X = pd.DataFrame({'Dated': [pd.Timestamp('2012-01-03 00:00:00'), 
                            pd.Timestamp('2012-01-04 00:00:00'), 
                            pd.Timestamp('2016-10-21 00:00:00')], 
                  'Val': [95812, 101265, 93594]}) 
 
fig, ax = plt.subplots() 
# ax.scatter(X['Dated'].tolist(), X['Val'], c='green', marker='.', s=200) 
ax.scatter(X['Dated'].values, X['Val'], c='green', marker='.', s=200) 
plt.show() 


Under the hood, the ax.scatter method calls

x = self.convert_xunits(x) 
y = self.convert_yunits(y) 

处理类似日期的输入。 convert_xunits 将 NumPy datetime64 数组转换为 Matplotlib datenums,但它将 Pandas 时间序列转换为 NumPy datetime64 数组。

因此,当 Pandas 时间序列作为输入传递给 ax.scatter 时,代码最终会在 this line is reached 时失败:

offsets = np.dstack((x, y)) 

np.dstack 尝试将其输入的数据类型提升为一种通用数据类型。如果 x 的数据类型为 datetime64[ns] 并且 y 的数据类型为 float64,则

TypeError: invalid type promotion 

被引发是因为没有与两者兼容的原生 NumPy dtype。