首页 > 解决方案 > 加快应用函数到 200 万行的 DataFrame

问题描述

我想在大约 200 万行的数据帧上运行 Mann Kendall 测试。

曼肯德尔测试功能:


def mk_test(x):

    alpha = 0.05
    n = len(x)
    # calculate S
    s = 0
    for k in range(n-1):
        for j in range(k+1, n):
            s += np.sign(x[j] - x[k])

    # calculate the unique data
    unique_x, tp = np.unique(x, return_counts=True)
    g = len(unique_x)

    # calculate the var(s)
    if n == g:  # there is no tie
        var_s = (n*(n-1)*(2*n+5))/18
    else:  # there are some ties in data
        var_s = (n*(n-1)*(2*n+5) - np.sum(tp*(tp-1)*(2*tp+5)))/18

    if s > 0:
        z = (s - 1)/np.sqrt(var_s)
    elif s < 0:
        z = (s + 1)/np.sqrt(var_s)
    else: # s == 0:
        z = 0

    # calculate the p_value
#     p = 2*(1-norm.cdf(abs(z)))  # two tail test
    h = abs(z) > norm.ppf(1-alpha/2)

    if (z < 0) and h:
        trend = 'decreasing'
    elif (z > 0) and h:
        trend = 'increasing'
    else:
        trend = 'no trend' 
        
    return trend

我想对每个客户 12 个月的收入运行上述函数,并将函数返回的值附加到数据框中。

示例数据框(list_df):

顾客 收入_1 收入_2
1234 100 100
5678 200 200

代码:

list_df['MK_Trend']=list_df.apply(mk_test,axis=1)

使用 apply 需要超过 4-5 小时才能完成代码。

请提出一种更快的方法来实现这一点。

标签: pythonloopsapplyrows

解决方案


推荐阅读