Search code examples
powerquerym

How can I expand all lists in a row of lists at the same time without repeating values?


In response to this question regarding how to expand all lists in a row of lists at the same time, @Carl Walsh kindly provided this succinct and helpful code:

let
Source = #table({"A", "B"}, {{ {1,2}, {3,4}} }),
Expanded = List.Accumulate(
    Table.ColumnNames(Source), 
    Source, 
    (state, column) => Table.ExpandListColumn(state, column))
in
Expanded

Which yields this:

enter image description here

I would like to get this result instead:

enter image description here

I don't want values repeated in previously processed columns as each follow-on column is processed.

Is there a simple modification to Carl's code that will get me there?


Solution

  • Maybe not really simple, but effective: the code below combines the columns with adjusted code so the lists are zipped and the inner lists are transformed into records. Next the list column is expanded, resulting in a column with nested records which are subsequently expanded.

    Unfortunately, you can't use combine columns with nested lists, so I created some dummy text columns first that I combined in order to generate the base code, which I subsequently adjusted and I removed the steps with the dummy columns.

    let
        Source = #table({"A", "B"}, {{ {1,2}, {3,4}} }),
        #"Merged Columns" = Table.CombineColumns(Source,{"A", "B"}, each List.Transform(List.Zip(_), each Record.FromList(_,{"A","B"})),"Merged"),
        #"Expanded Merged" = Table.ExpandListColumn(#"Merged Columns", "Merged"),
        #"Expanded Merged1" = Table.ExpandRecordColumn(#"Expanded Merged", "Merged", {"A", "B"}, {"A", "B"})
    in
        #"Expanded Merged1"