Search code examples
powerbipositionpowerqueryconditional-operator

Change column values based on its position


I'm trying to adjust some columns with negative values in my table, I want to all negative values be changed to 0,

The only problem is that the columns keep changing their names, so I would like to be able to make such adjustment based on column position,

For example, the columns are located in 3 and 4 position,

I have created a conditional column to adjust the negatives volumes,

#"New Column" = Table.AddColumn(#Previous Step", "New Column", each if OldColumnName < 0 then 0 else NewColumn),

Is there a way to make this conditional column based on the OldColumn position, and not by its name?


Solution

  • add column, custom column with formula

    = if Record.Field(_,Table.ColumnNames(Source){2})<0 then 0 else  Record.Field(_,Table.ColumnNames(Source){2})
    

    or

    = if Record.Field(_,Table.ColumnNames(Source){2})<0 then 0 else [some other column])
    

    where {2} is the position in column names

    Sample to transform in place to remove negatives

    Stepname = Table.TransformColumns(#"PriorStepNameHere",{{Table.ColumnNames(#"PriorStepNameHere"){2}, each if _<0 then 0 else _, Int64.Type}})
    

    for multiple column transformations

    let  Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    ColumnsToTransform = {Table.ColumnNames(Source){2},Table.ColumnNames(Source){3}},
    #"MultipleTransform" = Table.TransformColumns(Source, List.Transform(ColumnsToTransform,(x)=>{x, each if _<0 then 0 else _, type number}))
    in #"MultipleTransform"