Search code examples
excelpowerbipowerquerym

Removing Columns based on a list of index numbers -Power Query


I have a table, and I have a list of indexes.

Lets say the table is

Column A Column B Column C Column D
Cell 1
Cell 2

And the list is MyList={1,2}

Based on the list, which is the index of the Columns that needs to be removed, I would like to get a new table that consists of Column 0 and 3 which would be

Column A Column D
Cell 1
Cell 2

Of course in the actual scenario, the table sizes are dynamic, and the list is generated automatically. I need the M code for removing the columns based on the indexes in a list.

I am actually trying to remove the columns in the table where the values are the same. I have gotten so far to retrieving a list of indexes of the columns that need to be removed, and I would appreciate a help in pointing me in the right direction from here.


Solution

  • To remove columns based on array of column numbers

    let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    MyList={1,2},
    x = Table.RemoveColumns(Source,List.Transform(MyList, each Table.ColumnNames(Source){_}))
    in x
    

    To remove columns where contents of rows in that column are identical

    let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    #"Unpivoted Columns" = Table.UnpivotOtherColumns(Source, {}, "Attribute", "Value"),
    #"Grouped Rows" = Table.Group(#"Unpivoted Columns", {"Attribute"}, {{"Test", each  if List.Count(List.Distinct([Value]))=1 then true else false}}),
    x = Table.RemoveColumns(Source,Table.SelectRows(#"Grouped Rows", each ([Test] = true))[Attribute])
    in  x