KX Community

Find answers, ask questions, and connect with our KX Community around the world.
KX Community Guidelines

Home Forums kdb+ Unpack nested column in table Re: Unpack nested column in table

  • Laura

    Administrator
    September 6, 2022 at 12:00 am

    Assume here the column value is a matrix. Start with the new column names.

    q)show ncn:`$string[`b],/:string 1+til count first t`b `b1`b2`b3

    Pair them with the matrix columns.

    q)show d:ncn!flip t`b 
    b1| 4 6 12 
    b2| 5 12 36 
    b3| 6 23 14

     

    Heres the table with the nested column removed. (We use Functional qSQL rather than hard-code the column name.)

     

    q)show twc:![t;();0b;enlist`b] / table without column 
    a 
    - 
    1 
    2 
    3 
    
    q)twc,'flip d / Join Each new tuple 
    a b1 b2 b3 
    ---------- 
    1 4 5 6 
    2 6 12 23 
    3 12 36 14

     

    Putting it together:

     

    un:{[tbl;col] / un-nest col in tbl 
            mat:flip tbl col; / un-nest column 
            ncn:`$(,/:) . string(col;) 1+til count mat; / new column names 
            ![tbl;();0b;enlist col],'flip ncn!mat 
    }
    q)un[t;`b] 
    a b1 b2 b3 
    ---------- 
    1 4 5 6 
    2 6 12 23 
    3 12 36 14