如何计算往上/下数第一个大于当前行的值到当前行的距离

求两列特征,分别是往上数第一个大于f1值到当前f1的距离,以及往下数第一个大于当前f1值到现在的距离,如下图所示,

attachments-2023-09-vQyeRQss64f1d4691552e.jpg

当前行的值为11,往上数,第一个大于10的值为第一行的11,则距离为4,;往下第一个大于10的为最后一行12,则距离为2.

用kdb+实现代码如下图:

attachments-2023-09-mK0DehiS64f1d53706fa0.png

请问大佬能帮我改成ddb的形式吗?

请先 登录 后评论

1 个回答

wale

方法1:

f1 = 11 8 9 9 10 9 12
fx = eachRight(drop, isort f1, 1+rank f1) - til count f1
def findPrev(x): max iif(x<0, x, 00)
def findNext(x): min iif(x>0, x, 00)
table(f1, each(findPrev, fx) as f2, each(findNext, fx) as f3)

方法2,当vector比较大时,性能会更好一些:

f1 = 11 8 9 9 10 9 12
def dist(x, i) : ifirstHit(>, x.subarray(i:x.size()), x[i-1]) + 1
table(f1, each(dist{f1.reverse()}, size(f1)..1).replace!(0, 00) as f2, each(dist{f1}, 1..size(f1)).replace!(0, 00) as f3)
请先 登录 后评论