excelpowerquerymdynamic-tables

Calculating dynamic average columns by column name in PowerQuery


I have following data (simplified):

DATETIME VAL_A VAL_B VAL_C VAL_A_x
1.1.2025 1 2 3 4
2.1.2025 5 6 7 8

I need to calculate average value for EACH column (dynamic number) that has pair (VAL_A -> VAL_A_x) and REPLACE value in its mother column (VAL_A). Something VAL_A = (VAL_A + VAL_A_x)/2. Then I will delete columns ending with _x (It is simple). In the end, this is needed to achieve:

DATETIME VAL_A VAL_B VAL_C
1.1.2025 2.5 2 3
2.1.2025 7 6 7

I have a lot of columns without a pair to average with. I have a lot of rows. I don't like to transpose the whole table. Columns are decimal numbers.

I tried to filter columns that are ending with "_x"

= List.Select(Table.ColumnNames(Source), each Text.EndsWith(_,"_x")),

but not getting far from that.


Solution

  • The easiest would be to "transpose" or unpivot columns, then to pivot columns back again after doing a Group By with an extract text on the second occurrence of the delimiter.

    Example:

    let
        Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
        #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(Source, {"DATETIME"}, "Attribute", "Value"),
        #"Added Custom" = Table.AddColumn(#"Unpivoted Other Columns", "Column", each Text.BeforeDelimiter([Attribute], "_", 1)),
        #"Grouped Rows" = Table.Group(#"Added Custom", {"DATETIME", "Column"}, {{"Value", each List.Average([Value]), type number}}),
        #"Pivoted Column" = Table.Pivot(#"Grouped Rows", List.Distinct(#"Grouped Rows"[Column]), "Column", "Value", List.Sum)
    in
       #"Pivoted Column"
    

    Example