kdb排名函数与重复排名

huangapple go评论76阅读模式
英文:

q kdb rank function with duplicated ranks

问题

I can provide a translation of the code-related content:

标准实现中的 rank 函数如下:

rank 2 7 4 3 19 16 15 20 25 16 19

输出如下:

0 3 2 1 7 5 4 9 10 6 8

但我需要的是:

0 3 2 1 6 5 4 7 8 5 6
英文:

What would be an implementation of a q kdb function that does the same thing as the rank function but returns duplicated rank numbers for equal values?

In the standard implementation

rank 2 7 4 3 19 16 15 20 25 16 19

gives:

0 3 2 1 7 5 4 9 10 6 8

But I am looking for:

0 3 2 1 6 5 4 7 8 5 6

答案1

得分: 2

使用distinct来去除重复项,应用rank到该列表,然后创建一个字典来将这些排名映射回原始列表。

q)list:2 7 4 3 19 16 15 20 25 16 19

/ 创建字典
q)d!rank d:distinct list
2 | 0
7 | 3
4 | 2
3 | 1
19| 6
16| 5
15| 4
20| 7
25| 8

/ 将这些步骤封装成一个函数
q)rankDistinct:{(d!rank d:distinct x)x}

/ 应用到列表
q)rankDistinct list
0 3 2 1 6 5 4 7 8 5 6

或者,您也可以对distinct元素进行排序,然后使用find ?来获取排名,通过查找列表元素在已排序的不同元素中出现的位置。

q)rankDistinct2:{(asc distinct x)?x}

q)rankDistinct2 list
0 3 2 1 6 5 4 7 8 5 6
英文:

Can do that by using distinct to remove duplicates, applying rank to that list and then creating a dictionary to map those rankings back to the original list.

q)list:2 7 4 3 19 16 15 20 25 16 19

/ creating the dictionary
q)d!rank d:distinct list
2 | 0
7 | 3
4 | 2
3 | 1
19| 6
16| 5
15| 4
20| 7
25| 8

/ wrapping this up in a function
q)rankDistinct:{(d!rank d:distinct x)x}

/ applying to the list
q)rankDistinct list
0 3 2 1 6 5 4 7 8 5 6

Or alternatively you could sort the distinct elements and then use find ? to get the ranking by finding the index of where list elements appear in the distinct sorted elements.

q)rankDistinct2:{(asc distinct x)?x}

q)rankDistinct2 list
0 3 2 1 6 5 4 7 8 5 6

huangapple
  • 本文由 发表于 2023年3月23日 08:42:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75818389.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定