Sputnik2513
Sputnik2513

Reputation: 111

KDB/Q How to transpose a table?

How do you get the transpose of a table?

Say t:

    x          ltCt     poPt     kgAg     xoOt     woWa  yTri zapR    
    -----------------------------------------------------------------
    today      41.66    367.69   -662.89  11347.91 30644 -177 19149.92
    yesterday -1570.33 77233.76 -1169.33 11267.63 17079 5623 31069.08

and we want t2 to look like:

    x     |  today  yesterday
    ltCt  |  41.66  -1570.33
    poPt  |  367.69 77233.76
    ... 

I wish it was as simple as "flip t" but alas.

Upvotes: 3

Views: 8969

Answers (2)

Manish Patel
Manish Patel

Reputation: 4491

So here's the table (not keyed)

q)t
x         ltCt poPt kgAg xoOt woWa yTri zapR
--------------------------------------------
today     9    1    8    7    4    4    7
yesterday 2    8    1    2    5    2    8

Flip it to turn into a dictionary:

q)flip t
x   | today yesterday
ltCt| 9     2
poPt| 1     8
kgAg| 8     1
xoOt| 7     2
woWa| 4     5
yTri| 4     2
zapR| 7     8

You'll need some magic to turn it into a proper table:

q)flip ft[`x]!flip 1_ value ft:flip t
today yesterday
---------------
9     2
1     8
8     1
7     2
4     5
4     2
7     8

EDIT

Full transpose

q)flip raze[(key 1#ft),value( 1#ft)]!(enlist 1_key ft),flip value 1_ft:flip t
x    today yesterday
--------------------
ltCt 9     2
poPt 1     8
kgAg 8     1
xoOt 7     2
woWa 4     5
yTri 4     2
zapR 7     8

Upvotes: 4

terrylynch
terrylynch

Reputation: 13657

"flip" will do the job, just not on a keyed table. Was your table a keyed table by any chance? It looks like it was created using a select-by statement.

In that case try "flip 0!table"

Upvotes: 3

Related Questions