DolphinDB是否有Python argsort等效函数?如何实现字典排序?
在DolphinDB中实现城市人口字典的创建、筛选与排序
完整实现代码
// 1. 创建城市-人口字典(人口单位:万) cityPopulation = dict( ["北京", "上海", "广州", "深圳", "成都", "杭州"], [2154, 2428, 1530, 1344, 1658, 1193] ) // 2. 筛选人口超过1000万的城市 filteredCities = dict( keys(cityPopulation)[values(cityPopulation) > 1000], values(cityPopulation)[values(cityPopulation) > 1000] ) // 3. 按人口降序排序:替代argsort的实现 sortedIndices = xdesc(values(filteredCities)) sortedCities = dict( keys(filteredCities)[sortedIndices], values(filteredCities)[sortedIndices] ) // 输出结果 print(sortedCities)
核心问题解决:替代argsort的方案
DolphinDB中没有argsort函数,你可以用以下两种方式实现排序:
使用
xdesc/xasc获取排序索引xdesc(values(字典)):返回字典值按降序排列对应的原索引位置xasc(values(字典)):返回字典值按升序排列对应的原索引位置- 通过这些索引重新提取键和值,即可得到排序后的字典
转成表处理(可读性更强)
如果觉得字典操作繁琐,可以先将字典转换为表,用SQL语法完成筛选和排序,再转回字典:
// 转表处理流程 cityTable = table(keys(cityPopulation) as city, values(cityPopulation) as population) filteredTable = select * from cityTable where population > 1000 sortedTable = select * from filteredTable order by population desc sortedCities = dict(sortedTable.city, sortedTable.population)
内容的提问来源于stack exchange,提问作者Elsa
相关产品推荐
相关产品推荐

