在分组q表中将x1列的数据类型同步至后续列
问题:同步列组内数据类型的最优实现方案
数据
q) t:([] sym1: 1 2 3 4 5 6 7; sym2: 1.1 2.2 3.3 4.4 5.5 6.6 7.7; sym3: 2.1 3.2 4.3 5.4 6.5 7.6 8.7; sym4: 3.1 4.2 5.3 6.4 7.5 8.6 9.7; sym5: 4.1 5.2 6.3 7.4 8.5 9.6 10.7; sym6: 5.1 6.2 7.3 8.4 9.5 10.6 11.7; sym7: 6.1 7.2 8.3 9.4 10.5 11.6 12.7; age1: (`x1;`x2;`x3;`x4;`x5;`x6;`x7); age2: (`x1;"x2";"x3";"x4";"x5";"x6";"x7"); age3: (`x1;"x2";"x3";"x4";"x5";"x6";"x7"); age4: (`x1;"x2";"x3";"x4";"x5";"x6";"x7"); age5: (`x1;"x2";"x3";"x4";"x5";"x6";"x7"); age6: (`x1;"x2";"x3";"x4";"x5";"x6";"x7"); age7: (`x1;"x2";"x3";"x4";"x5";"x6";"x7"); time1: (`x1;`x2;`x3;`x4;`x5;`x6;`x7); time2: (`x1;"x2";"x3";"x4";"x5";"x6";"x7"); time3: (`x1;"x2";"x3";"x4";"x5";"x6";"x7"); time4: (`x1;"x2";"x3";"x4";"x5";"x6";"x7"); time5: (`x1;"x2";"x3";"x4";"x5";"x6";"x7"); time6: (`x1;"x2";"x3";"x4";"x5";"x6";"x7"); time7: (`x1;"x2";"x3";"x4";"x5";"x6";"x7"))
已执行语句
q)strCols:string cols t q)strCols "sym1" "sym2" "sym3" "sym4" "sym5" "sym6" "sym7" "age1" "age2" "age3" "age4" "age5" "age6" "age7" "time1" "time2" "time3" "time4" "time5" "time6" "time7" q)cols1:{(-1_x),"*"}each strCols[til[floor count[strCols]%7]*7] q)cols1 "sym*" "age*" "time*" q)ind:{where strCols like x}each cols1 q)ind 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 q)indCols:{1_`$strCols[x]}each ind q)indCols sym2 sym3 sym4 sym5 sym6 sym7 age2 age3 age4 age5 age6 age7 time2 time3 time4 time5 time6 time7 q)typeCols:{type t[x]}each `${(-1_x),"1"}each cols1 q)typeCols 11 7 7h
尝试的自定义函数
castFunc:{{ [col1;col2;col3;col4;col5;col6;typ] ![t;();0b;(`col1`col2`col3`col4`col5`col6)!((mmu;typ;col1);(mmu;typ;col2);(mmu;typ;col3);(mmu;typ;col4);(mmu;typ;col5);(mmu;typ;col6))] }[x[0];x[1];x[2];x[3];x[4];x[5];y] }'[indCols;typeCols]
需求说明
需要编写一个函数,将sym、age、time等列组中x1列的数据类型,同步赋值给同组内x2至x7的其余列。使用函数式更新遍历列与数据类型时遇到问题,寻求最优实现方案。
最优实现方案
利用Kdb+的分组和批量更新特性,可简化代码逻辑,避免硬编码列名:
// 处理单个列组的函数 castGroup:{[t;groupPrefix] // 筛选当前组的所有列 groupCols:cols t where string cols t like groupPrefix,"*"; // 获取组内首列的目标类型 targetType:type t[first groupCols]; // 确定需要更新的列(排除首列) updateCols:1_groupCols; // 批量执行类型转换更新 ![t;();0b;updateCols!{(mmu;targetType;x)}each updateCols] } // 自动识别所有列组前缀 groupPrefixes:distinct {-1_x}each string cols t where string cols t like "*1"; // 遍历所有列组完成更新 updatedT:{castGroup[x;y]}[t]/:groupPrefixes;
方案说明
castGroup函数:接收表和列组前缀,自动完成该组的类型同步:- 筛选该前缀下的所有列
- 获取组内首列(如
sym1)的数据类型 - 对组内其余列执行类型转换的函数式更新
- 自动识别列组:通过提取所有以
1结尾的列的前缀,自动识别sym、age、time等列组,无需手动指定 - 可扩展性:使用
/:遍历所有列组,后续新增列组无需修改代码,直接兼容
执行后,updatedT即为完成所有列组类型同步后的表。
内容的提问来源于stack exchange,提问作者threedom
相关产品推荐
相关产品推荐

