joh*_*mon 5 python for-loop scipy pearson-correlation
我有一个名为“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
Run Code Online (Sandbox Code Playgroud)
目标
我正在尝试使用“for 循环”来计算“权重”变量在不同时间范围或时间间隔内的百分比变化之间的相关性。这样做是为了评估不同时间段内饲养牲畜的影响。
该循环可以在下面找到:
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))
Run Code Online (Sandbox Code Playgroud)
该循环执行良好,但是在计算 pearsonr 相关性和 p 值时失败,即在本节中:
(correlation, p-value)=pearsonr(weight_change_lagged[not_na], weight_change_future[not_na])
Run Code Online (Sandbox Code Playgroud)
它会生成此错误:
类型错误:没有为 ufunc add 找到与指定签名和转换匹配的循环
有人知道如何解决我的问题吗?我浏览了论坛,没有找到符合我确切要求的答案。
通过随机修补,我设法解决了我的问题,如下:
scipy 的 pearsonr 包仅接受数组或类似数组的输入。这意味着:
然而,变量的完整 Pandas Dataframes,即使它们包含一列,也不起作用。
因此,我将有问题的代码段编辑如下:
# 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'])
Run Code Online (Sandbox Code Playgroud)
只需稍加修改,代码就可以顺利执行。
笔记:
如果您使用双方括号,如下所示,您输入的是 pandas 数据帧而不是序列,并且 pearsonr 函数将抛出错误:
weight_change_future[['Weight']]
Run Code Online (Sandbox Code Playgroud)
感谢所有试图提供帮助的人,你们的问题让我找到了答案。
| 归档时间: |
|
| 查看次数: |
12924 次 |
| 最近记录: |