kdb中如何将多列合并为一列?

How to combine multiple columns into one column in kdb?

我写了下面的有效代码,但我认为会有更好的方法来解决这个问题。

我有这样的东西

table:([]time:9 11;Bid1px:4 5;Bid2px:7 3;Bid3px:6 8);
time Bid1px Bid2px Bid3px
-------------------------
9    4      7      6
11   5      3      8
table:update All_bid:flip(Bid1px;Bid2px;Bid3px) from table;
time Bid1px Bid2px Bid3px All_bid
---------------------------------
9    4      7      6      4 7 6
11   5      3      8      5 3 8

我想像下面这样使用 Bidcols 编写代码,但似乎找不到方法,我们将不胜感激。

Bidcols:`Bid1px`Bid2px`Bid3px;
table:update All_bid:flip(Bidcols????) from table;

一种方法是使用 #(获取),在 table 上将 return 列的子集。由于 kdb 中的 table 只是一个字典列表,因此可以在 table 上使用 value each 来获取每一行的值:

q)table:([]time:9 11;Bid1px:4 5;Bid2px:7 3;Bid3px:6 8)
q)Bidcols:`Bid1px`Bid2px`Bid3px;
q)// using just #, all_bid column is a table so each row is a dict
q)update all_bid:Bidcols#table from table
time Bid1px Bid2px Bid3px all_bid
-----------------------------------------------------
9    4      7      6      `Bid1px`Bid2px`Bid3px!4 7 6
11   5      3      8      `Bid1px`Bid2px`Bid3px!5 3 8
q)// adding value each gives us the final desired result
q)update all_bid:value each Bidcols#table from table
time Bid1px Bid2px Bid3px all_bid
---------------------------------
9    4      7      6      4 7 6
11   5      3      8      5 3 8

一种方法是通过索引。

q)Bidcols:`Bid1px`Bid2px`Bid3px
q)show table:([]time:9 11;Bid1px:4 5;Bid2px:7 3;Bid3px:6 8)
time Bid1px Bid2px Bid3px
-------------------------
9    4      7      6
11   5      3      8

q)update all_bid:flip table Bidcols from table
time Bid1px Bid2px Bid3px all_bid
---------------------------------
9    4      7      6      4 7 6
11   5      3      8      5 3 8

为了解释这一点,首先我们用 Bidcols 索引到 table:

q)table Bidcols
4 5
7 3
6 8

这 return 是一个列表列表 - Bidcols 中的每个列名称一个列表。 然后我们 flip 这个到 return 另一个列表列表 - 这次等于 table

的长度
q)flip table Bidcols
4 7 6
5 3 8

为了完整起见,虽然 Seans 和 Jonathons 的答案是针对此用例的更好解决方案,但解决像您这样的问题(试图使 select 语句更具可配置性)的更通用方法是将其转换功能性 select 语句。

在这个例子中它将是:

/use parse to determine functional form
q)0N!parse"update All_bid:flip(Bid1px;Bid2px;Bid3px) from table";
(!;`table;();0b;(,`All_bid)!,(+:;(enlist;`Bid1px;`Bid2px;`Bid3px)))

/replicate the functional form, swapping in your Bidcols list
q)![table;();0b;(1#`All_bid)!enlist(flip;enlist,Bidcols)]
time Bid1px Bid2px Bid3px All_bid
---------------------------------
9    4      7      6      4 7 6
11   5      3      8      5 3 8