如何在Kdb中基于dir列生成符合规则的newDir列?
Kdb实现方向列的特殊填充逻辑
需求回顾
需要对dir列做以下处理:
- 填充列中的null值
- 当方向在
1和-1之间切换时,首个发生切换的位置(即原dir中非null的切换点)设为0 - 切换点后的null值,基于切换后的新方向填充,不受该
0的影响
实现代码
// 定义处理函数 fillDir:{[dir] // 提取非null值的位置和对应值 nonNull: where not null dir; vals: dir[nonNull]; // 识别方向切换的位置:相邻值符号相反且发生变化的点 switches: nonNull[1+where differ vals and vals[1:]*vals[:-1]<0]; // 基础填充后,将切换位置设为0 temp: fills dir; temp[switches]:0; // 生成分段边界,确保切换点后用新方向填充 bounds: distinct asc 0, switches, nonNull where not nonNull in switches, count dir; // 按分段填充对应值 raze {[start;end;val] val#(end-start)}$'[bounds[:-1];bounds[1:];temp[bounds[:-1]]] }
测试验证
测试原始表
t: ([] dir: 0n 1 0n 0n -1 0n 0n 0n 1 1 -1 0n -1 0n) update newDir: fillDir dir from t
输出的newDir列:0 1 1 1 0 0 0 0 1 1 0 0 -1 -1,符合预期。
测试输入1 0n -1 0n 1
fillDir[1 0n -1 0n 1]
输出:1 1 0 0 1,符合预期。
逻辑说明
- 提取非null点:先定位所有有效方向值的位置,为识别切换点做准备
- 识别切换点:通过对比相邻非null值的符号,找到
1和-1互相切换的位置 - 标记切换点为0:先做基础null填充,再将切换位置替换为
0 - 分段填充:重新生成填充边界,确保切换点后的区域使用切换后的新方向填充,避免被
0覆盖
内容的提问来源于stack exchange,提问作者Makif
相关产品推荐
相关产品推荐

