Power Query: transform a column by multiplying by another column

前端 未结 3 2100
余生分开走
余生分开走 2021-01-19 19:27

I want to do something similar to Power Query Transform a Column based on Another Column, but I\'m getting stuck on how to modify the syntax for my particular goal.

3条回答
  •  走了就别回头了
    2021-01-19 19:49

    Table.TransformColumns won't give you Column A unless you can index back into the table, which will only be possible if your columns only have unique data.

    Table.TransformRows will let you build new rows with whatever logic you want:

    let
        Source = Csv.Document("Column A,Column B,Column C
            1,4,7
            2,5,8
            3,6,9"),
        PromotedHeaders = Table.PromoteHeaders(Source),
        ChangedType = Table.TransformColumnTypes(PromotedHeaders,{{"Column A", type number}, {"Column B", type number}, {"Column C", type number}}),
    
        MultipliedRows = Table.FromRecords(Table.TransformRows(ChangedType, 
            each [
                Column A = [Column A],
                Column B = [Column A] * [Column B],
                Column C = [Column A] * [Column C]
            ]))
    in
        MultipliedRows
    

    This works well for columns B and C, but if you need B through Z you might want fancier logic to avoid repeating yourself.

    EDIT: A more general solution for many columns is to use Record.TransformFields on a list of transforms for all column names except "Column A".

    let
        Source = Csv.Document("Column A,Column B,Column C,D,E,F
            1,4,7,1,2,3
            2,5,8,4,5,6
            3,6,9,7,8,9"),
        PromotedHeaders = Table.PromoteHeaders(Source),
        ChangedType = Table.TransformColumnTypes(PromotedHeaders,{{"Column A", type number}, {"Column B", type number}, {"Column C", type number}, {"D", type number}, {"E", type number}, {"F", type number}}),
    
        MultipliedRows = Table.FromRecords(Table.TransformRows(ChangedType, (row) => 
            let
                ColumnA = row[Column A],
                OtherColumns = List.RemoveItems(Record.FieldNames(row), {"Column A"}),
                Transforms = List.Transform(OtherColumns, (name) => { name, (cell) => cell * ColumnA })
            in
                Record.TransformFields(row, Transforms)))
    in
        MultipliedRows
    

提交回复
热议问题