Search code examples
kdbk

Reshape [cols;table]


How do I get columns from a table? If they don't exist it's ok to get them as null columns.

Trying reshape#:

q)d:`a`b!1 2
q)enlist d
a b
---
1 2
q)`a`c#d
a| 1
c|
q)`a`c#enlist d
'c
  [0]  `a`c#enlist d
           ^

Why does thereshape# operator not work on a table? It could easily act on each row (which is dict) and combine results. So I'm forced to write:

q)`a`c#/:enlist d
a c
---
1

Is it the shortest way?


Solution

  • Any key you try to take (#) which is not present in a dictionary will be assigned a null value of the same type as the first value in the dictionary. Similar behaviour is not available for tables.

    q)`a`c#`a`b!(1 2;())
    a| 1 2
    c| `long$()
    q)`b`c#`a`b!(();1 2)
    b| 1 2
    c| ()
    

    Like you mentioned, the use of each-right (/:) will act on each row of the table IE each dictionary. Instead of using an iterator to split the table into dictionaries we can act on the dictionary itself. This will return the same output and is slightly faster.

    q)d:`a`b!1 2
    q)enlist`a`c#d
    a c
    ---
    1
    q)(`a`c#/:enlist d)~enlist`a`c#d
    1b
    q)\ts:1000000 enlist`a`c#d
    395 864
    q)\ts:1000000 `a`c#/:enlist d
    796 880