英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论