Forum Discussion

osama_ayoub's avatar
osama_ayoub
Helper III
2 years ago
Solved

Transform some columns based on condition

Hi, I have a Table with columns of Material and Consumptions by months and Years , what I want is to check in every rowif the material begins with "TV-" then I would to transform some corresponding ...
  • ronrsnfld's avatar
    2 years ago

    I second what dufoq3 wrote regarding posting your data as text and also showing your expected results from that data.

     

    But you should be able to adapt the below code to your real data.

    Note that this can all be done in a single step using the Table.ReplaceValue function.

     

    Sample Data

     

    let
    
    //change next lines to reflect your actual data source
        Source = Excel.CurrentWorkbook(){[Name="Table31"]}[Content],
        #"Changed Type" = Table.TransformColumnTypes(Source,{
            {"Column1", type text}, {"Column2", Int64.Type}, {"Column3", Int64.Type}, {"Column4", Int64.Type}, {"Column5", Int64.Type}, {"Column6", Int64.Type}, {"Column7", Int64.Type}, {"Column8", Int64.Type}, {"Column9", Int64.Type}, {"Column10", Int64.Type}}),
    
        #"Replace tv with 0" = Table.ReplaceValue(
            #"Changed Type",
            each [Column1],
            0,
            (x,y,z)=> if Text.StartsWith(y,"TV-") then 0 else x,
    
        //This line is a list of the columns you wish to have changed to 0
        //In my example, I chose all the data columns by removing the first column from the list
        //   but you can be more selective
            List.RemoveFirstN(Table.ColumnNames(#"Changed Type"),1))
    in
        #"Replace tv with 0"

     

    Results 

     

     

     

     

     

  • ronrsnfld's avatar
    ronrsnfld
    2 years ago

    x = current value 

    y = old value

    z = replacement value

     

    IOW:

    #"Replace tv with 0" = Table.ReplaceValue(
            #"Changed Type",
            each [Column1], //y
            0,              //z
            (x,y,z)=> if Text.StartsWith(y,"TV-") then z else x,
            List.RemoveFirstN(Table.ColumnNames(#"Changed Type"),1))    //x

     

    Note that I can replace the 0 with z in the function and will obtain the same result.

     

    See the Help topic for that function for other examples.