python实现Theil-Sen Median斜率估计和Mann-Kendall趋势分析

python实现Theil-Sen Median斜率估计和Mann-Kendall趋势分析

我的输入数据长这样,直接上代码

python实现Theil-Sen Median斜率估计和Mann-Kendall趋势分析_第1张图片

# -*- codeing = utf-8 -*-

import numpy as np
from scipy.stats import norm
import pandas as pd

path = r'F:\UHI\驱动力分析\python.xlsx'#文件路径
df = pd.read_excel(path, sheet_name='uhi')#表单


def sen_slope(x):
    """
    计算 Sen's 斜率估计值
    """
    n = len(x)
    slopes = []
    for i in range(n):
        for j in range(i + 1, n):
            slopes.append((x[j] - x[i]) / (j - i))
    return np.median(slopes)


def mann_kendall(x):
    """
    计算 Mann-Kendall 检验的统计量、Z 值和 p 值
    """
    n = len(x)
    s = 0
    for i in range(n - 1):
        for j in range(i + 1, n):
            s += np.sign(x[j] - x[i])
    var_s = n * (n - 1) * (2 * n + 5) / 18
    if s > 0:
        z = (s - 1) / np.sqrt(var_s)
    elif s < 0:
        z = (s + 1) / np.sqrt(var_s)
    else:
        z = 0
    p = 2 * (1 - norm.cdf(abs(z)))
    return s, z, p


for y in range(0, 45):  # 45行excel记录
    xi = list(df.loc[y].values)
    # print(xi)
    xii = xi[1:]
    # print(xii)
    x = xii

    slop = sen_slope(x)
    s, z, p = mann_kendall(x)

    print(slop, s, z, p)
    # print("Sen's slope:", slop)
    # print("Mann-Kendall statistic:", s)
    # print("Mann-Kendall检验的Z值:", z)
    # print("Mann-Kendall p-value:", p)

你可能感兴趣的:(python,numpy,开发语言)