关于“No loop matching the specified signature and casting was found for ufunc lstsq_n”问题的解决

下面这段代码是使用MatPlotLib绘制数据随时间变化的趋势。

import datetime as dt
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.pylab as plb

plt.rcParams['font.sans-serif'] = ['SimHei']        # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False         # 用来正常显示负号

df = pd.DataFrame(columns=('Time', 'Sales'))

start_date = dt.datetime(2022, 7, 1)
end_date = dt.datetime(2022, 7, 10)
daterange = pd.date_range(start_date, end_date)

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(15, 5))

for single_date in daterange:
    row = dict(zip(['Time', 'Sales'], [single_date, int(50 * np.random.rand(1))]))
    row_s = pd.Series(row)
    row_s.name = single_date.strftime('%b %d')
    df = df.append(row_s)


df.loc['Jul 01': 'Jul 07', ['Sales']].plot(ax=axes[0])
axes[0].set_ylim(0, 50)
axes[0].set_xlabel('Sales Date')
axes[0].set_ylabel('Sale Value')
axes[0].set_title('在轴上表示时间')
axes[0].grid()

# 标绘随时间的趋势
df.loc['Jul 01': 'Jul 07', ['Sales']].plot(ax=axes[1])

xx = np.arange(0, 10).flatten() * 1.0
yy = df['Sales'].values.flatten() * 1.0

# 下面的print用于调试,正式代码中可删除
print('xx: ', xx)
print('type(xx): ', type(xx))
print('type(xx[0]): ', type(xx[0]))
print('xx shape: ', xx.shape)
print('yy: ', yy)
print('type(yy): ', type(yy))
print('type(yy[0]): ', type(yy[0]))
print('yy shape: ', yy.shape)
# 上面的print用于调试,正式代码中可删除

z1 = np.polyfit(xx, yy, 1)
p1 = np.poly1d(z1)
plb.plot(xx, p1(xx), 'm-')
axes[1].set_ylim(0, 50)
axes[1].set_xlabel('Sales Date')
axes[1].set_ylabel('Sale Value')
axes[1].set_title('标绘随时间的趋势')
axes[1].legend(['Sales', 'Trend'])
axes[1].grid()

上面代码在最初运行时,并没有中间一大段print,当执行到z1 = np.polyfit(xx, yy, 1)时报错,在一大段错误信息最后,有一句“TypeError: No loop matching the specified signature and casting was found for ufunc lstsq_n” 。大致意思是:没有找到符合指定签名和特征的循环。
在查找原因的过程中,看到一篇文章【pearsonr计算相关性时报错:No loop matching the specified signature and casting was found for ufunc add】,其描述的错误现象和上面错误基本相同。于是尝试按照文章中的思路来解决,也才有了上面代码中大段的print。

注意到xx和yy不相同的地方是:xx中元素的类型是:numpy.float64,而yy中元素的类型是float,可能这就是产生错误的原因。于是把生成yy的语句由原来的yy = df['Sales'].values.flatten() * 1.0,改为yy = np.array(df['Sales'].values * 1.0, dtype='float64').flatten(),再次运行后没有报错,并绘制出相应的图形。