You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Series重置后的数值索引提取存入数组用于线性回归

时间序列线性回归的X/Y数组提取方案

你已经通过A.reset_index()将日期索引转为普通列,同时生成了从0开始的数值型索引,接下来可以按以下方式提取X、Y数组:

步骤1:保存重置索引后的DataFrame

reset_index()会返回一个新的DataFrame,需要先赋值保存:

A_reset = A.reset_index()

步骤2:提取X数组(数值索引)

直接提取重置后的自动生成索引,转成numpy数组即可:

import numpy as np
X = A_reset.index.values

或者更直接的方式,无需依赖重置后的索引,直接生成连续整数序列:

X = np.arange(len(A_reset))

两种方式都能得到符合线性回归要求的数值型X数组。

步骤3:提取Y数组(待分析数据)

假设你的目标数据列名为target_col(替换成你实际的列名),提取为numpy数组:

Y = A_reset['target_col'].values

完整示例(结合你的现有代码)

import numpy as np
import matplotlib.pyplot as plt

def estimate_coef(x, y):
    # 样本数量
    n = np.size(x)

    # x和y的均值
    m_x = np.mean(x)
    m_y = np.mean(y)

    # 计算交叉偏差与x的偏差
    SS_xy = np.sum(y*x) - n*m_y*m_x
    SS_xx = np.sum(x*x) - n*m_x*m_x

    # 计算回归系数
    b_1 = SS_xy / SS_xx
    b_0 = m_y - b_1*m_x

    return (b_0, b_1)

def plot_regression_line(x, y, b):
    # 绘制原始数据散点图
    plt.scatter(x, y, color = "m", marker = "o", s = 30)

    # 预测值向量
    y_pred = b[0] + b[1]*x

    # 绘制回归线
    plt.plot(x, y_pred, color = "g")

    # 设置标签
    plt.xlabel('时间步长')
    plt.ylabel('目标数据')

    # 显示图像
    plt.show()

# 数据处理
A_reset = A.reset_index()
X = A_reset.index.values
Y = A_reset['target_col'].values  # 替换为你的实际列名

# 计算回归系数并判断趋势
b = estimate_coef(X, Y)
print(f"截距:{b[0]:.4f},斜率:{b[1]:.4f}")

# 加入小阈值避免浮点精度误差影响判断
if b[1] > 0.001:
    print("时间序列呈上升趋势")
elif b[1] < -0.001:
    print("时间序列呈下降趋势")
else:
    print("时间序列趋于平稳")

# 绘制回归线
plot_regression_line(X, Y, b)

内容的提问来源于stack exchange,提问作者Spearitch502

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 10:20:42