關於「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(),再次運行後沒有報錯,並繪製出相應的圖形。