Pearsonr: TypeError: No loop matching the specified signature and casting was found for ufunc add

Pearsonr: TypeError: No loop matching the specified signature and casting was found for ufunc add

我有一个名为 "df" 的时间序列 Pandas 数据框。它具有一列和以下形状:(2000, 1)。下面数据帧的头部显示了它的结构:

            Weight
Date    
2004-06-01  1.9219
2004-06-02  1.8438
2004-06-03  1.8672
2004-06-04  1.7422
2004-06-07  1.8203

目标

我正在尝试使用 "for-loop" 来计算 "Weight" 变量在不同时间范围或时间滞后的百分比变化之间的相关性。这样做是为了评估在不同时间段内饲养牲畜的影响。

循环可以在下面找到:

from scipy.stats.stats import pearsonr

# Loop for producing combinations of different timelags and holddays 
# and calculating the pearsonr correlation and p-value of each combination 

for timelags in [1, 5, 10, 25, 60, 120, 250]:
    for holddays in [1, 5, 10, 25, 60, 120, 250]:
        weight_change_lagged = df.pct_change(periods=timelags)
        weight_change_future = df.shift(-holddays).pct_change(periods=holddays)

        if (timelags >= holddays):
            indepSet=range(0, weight_change_lagged.shape[0], holddays)
        else:
            indepSet=range(0, weight_change_lagged.shape[0], timelags)

        weight_change_lagged = weight_change_lagged.iloc[indepSet]
        weight_change_future = weight_change_future.iloc[indepSet]

        not_na = (weight_change_lagged.notna() & weight_change_future.notna()).values

        (correlation, p-value)=pearsonr(weight_change_lagged[not_na], weight_change_future[not_na])
        print('%4i %4i %7.4f %7.4f' % (timelags, holddays, correlation, p-value))

循环执行得很好,但是,在计算 pearsonr 相关性和 p 值时它失败了,即在这一部分:

(correlation, p-value)=pearsonr(weight_change_lagged[not_na], weight_change_future[not_na])

它生成此错误:

TypeError: no loop matching the specified signature and casting was found for ufunc add

有人知道如何解决我的问题吗?我 looked through the forums 没有找到符合我确切要求的答案。

通过随机修补,我设法解决了我的问题如下:

scipy 的 pearsonr 包只接受数组或类似数组的输入。这意味着:

  • 输入变量的 Numpy 数组有效。
  • Pandas 输入变量系列工作。

但是,完整的 Pandas 变量数据框,即使它们包含一列,也不起作用。

因此,我将有问题的代码段编辑如下:

# Define an object containing observations that are not NA
not_na = (weight_change_lagged.notna() & weight_change_future.notna()).values

# Remove na values before inputting the data into the peasonr function (not within the function as I had done):
weight_change_lagged = weight_change_lagged[not_na]
weight_change_future = weight_change_future[not_na]

# Input Pandas Series of the Future and Lagged Variables into the function
(correlation, p-value)=pearsonr(weight_change_lagged['Weight'], weight_change_future['Weight'])

只需稍微修改一下,代码就可以顺利执行。

注:

如果您使用双方括号,如下所示,您输入的是 pandas 数据帧而不是系列,pearsonr 函数将抛出错误:

weight_change_future[['Weight']]

感谢所有试图提供帮助的人,你们的问题让我找到了答案。

就我而言,这不是数据类型问题,而是维度错误。感谢文章https://programmersought.com/article/67803965109/

即使您在函数中输入 numpy 数组,也可能会遇到此错误。结果是 numpy 数组引入的“额外”维度导致了这个问题。 W

np_data.shape
>> (391, 1)

这个(..,1)才是问题的根源。您可以使用 np.squeeze(np_data) 删除此维度以仅提取数组的值,因为

np.squeeze(np_data).shape
>> (391,)

总而言之,解决方案是使用:

pearson, pvalue = pearsonr(np.squeeze(np_data_a), np.squeeze(np_data_b))