用ACF和PACF计算出一堆数据的周期个数以及周期时长,数据分析python

具体步骤

1使用ACF和PACF:可以通过查看ACF图中的周期性峰值,找到数据中的周期性。如果ACF图在某个滞后期处出现显著的正相关峰值,并且这种模式在多个滞后周期中重复出现,这就是周期性信号的特征。而PACF则可以帮助确定延迟的直接影响。

2找周期数和周期长度:周期的时长可以通过ACF中第一个显著的峰值(排除滞后期为0时的峰值)来确定,而周期的个数则可以通过分析整个序列中的周期性重复次数来估计。

下面是一个使用 statsmodels 库来计算并绘制ACF和PACF,并分析周期的Python代码。

python 复制代码
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from statsmodels.tsa.stattools import acf, pacf

# 生成模拟数据或导入真实数据
# 假设你的数据是一个时间序列 DataFrame 或 NumPy 数组
# data = pd.read_csv('your_data.csv')  # 你的真实数据
data = np.sin(np.linspace(0, 10 * np.pi, 500))  # 模拟数据

# 绘制ACF和PACF
fig, ax = plt.subplots(2, 1, figsize=(10, 8))

# ACF图
plot_acf(data, lags=50, ax=ax[0])
ax[0].set_title('Autocorrelation (ACF)')

# PACF图
plot_pacf(data, lags=50, ax=ax[1])
ax[1].set_title('Partial Autocorrelation (PACF)')

plt.tight_layout()
plt.show()

# 计算ACF和PACF值
acf_values = acf(data, nlags=50)
pacf_values = pacf(data, nlags=50)

# 寻找周期长度
def find_period(acf_values):
    # 查找第一个显著峰值的位置作为周期
    for lag in range(1, len(acf_values)):
        if acf_values[lag] > 0.5:  # 设定一个阈值,例如0.5,可以调整
            return lag
    return None

period = find_period(acf_values)
print(f"Detected period length: {period}")
python 复制代码
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from statsmodels.tsa.stattools import acf, pacf

# 生成模拟数据或导入真实数据
data = np.sin(np.linspace(0, 20 * np.pi, 1000))  # 生成正弦波数据,假设有多个周期

# 绘制ACF和PACF
fig, ax = plt.subplots(2, 1, figsize=(10, 8))

# ACF图
plot_acf(data, lags=100, ax=ax[0])
ax[0].set_title('Autocorrelation (ACF)')

# PACF图
plot_pacf(data, lags=100, ax=ax[1])
ax[1].set_title('Partial Autocorrelation (PACF)')

plt.tight_layout()
plt.show()

# 计算ACF值
acf_values = acf(data, nlags=100)

# 寻找周期长度函数
def find_period(acf_values, threshold=0.5):
    # 查找第一个显著峰值的位置作为周期长度
    for lag in range(1, len(acf_values)):
        if acf_values[lag] > threshold:  # 使用阈值筛选显著峰值
            return lag
    return None

# 确定周期长度
period_length = find_period(acf_values)
print(f"Detected period length: {period_length}")

# 计算周期个数
if period_length:
    total_data_points = len(data)
    num_periods = total_data_points // period_length
    print(f"Detected number of periods: {num_periods}")
else:
    print("No significant period detected.")
相关推荐
C++业余爱好者21 分钟前
Java 提供了8种基本数据类型及封装类型介绍
java·开发语言·python
老蒋新思维23 分钟前
创客匠人峰会深度解析:知识变现的 “信任 - 效率” 双闭环 —— 从 “单次交易” 到 “终身复购” 的增长密码
大数据·网络·人工智能·tcp/ip·重构·数据挖掘·创客匠人
AI Echoes1 小时前
构建一个LangChain RAG应用
数据库·python·langchain·prompt·agent
派大鑫wink2 小时前
从零到精通:Python 系统学习指南(附实战与资源)
开发语言·python
c骑着乌龟追兔子2 小时前
Day 38 官方文档的阅读
python
羸弱的穷酸书生2 小时前
国网 i1协议 python实现
开发语言·python
weixin_462022352 小时前
RAW-Adapter: Adapting Pre-trained Visual Model to Camera RAW Images
python·计算机视觉
电子硬件笔记2 小时前
Python语言编程导论第三章 编写程序
开发语言·python·编辑器
布谷歌2 小时前
在java中实现c#的int.TryParse方法
java·开发语言·python·c#