Search code examples
excelpowerbipowerquerym

Insert new column with list of values in PowerQuery/M


If I have the following source:

#"My Source" = Table.FromRecords({
        [Name="Jared Smith", Age=24],
        [Name = "Tom Brady", Age=44],
        [Name="Hello Tom", Age = null],
        [Name = "asdf", Age = "abc"]
    }),

How would I add a new column from a list of values, for example:

Table.AddColumn(#"My Source", "New Col", {'x', 'y', 'z', null})

Now my table would have three columns. How could this be done?


Solution

  • Here's another way. It starts similarly to the approach used by Ron, by adding an index, but then instead of using merge it just uses the index as a reference to the appropriate list item.

    let
        Source1 = Table.FromRecords({
            [Name="Jared Smith", Age=24],
            [Name = "Tom Brady", Age=44],
            [Name="Hello Tom", Age = null],
            [Name = "asdf", Age = "abc"]
        }),
        #"Added Index" = Table.AddIndexColumn(Source1, "Index", 0, 1),
        #"Added Custom" = Table.AddColumn(#"Added Index", "Custom", each {"x", "y", "z", null}{[Index]}),
        #"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Index"})
    in
        #"Removed Columns"