python - 加快应用函数到 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 小时才能完成代码。
请提出一种更快的方法来实现这一点。
解决方案
推荐阅读
- java - 简单的 HTML5 游戏在 android WebView 中不起作用
- python - 如果在熊猫的给定列中找到字符串匹配,则获取另一列的单元格值
- flutter - 如何通过颤动在屏幕上的某处点击来隐藏覆盖
- java - 使用 setter 方法更新 Room Database 中特定 ID 的特定字段
- installation - 安装程序 EXE 无法启动 - 没有任何错误消息
- linux - 如何使用 Bash 在电子邮件的消息正文中插入新行?
- reactjs - Docker compose:react app 和 nginx 之间共享静态卷
- go - 在数据库中编组 JSON 字段以使用 Pop 进行结构
- python - 获取 AttributeError:模块“aws_cdk.aws_cognito”没有属性“UserPoolResourceServer”错误
- string - 删除包含特定字符串的重复快捷方式