Forum Discussion

victoire0's avatar
victoire0
Regular Visitor
6 years ago
Solved

Renaming colomns

Hi everyone,    Do you know how I can do the following ? : I would like to rename specific columns by keeping only the 2 digits left and adding a "W" in front (I'm working on weeks so 012020 will b...
  • edhans's avatar
    edhans
    6 years ago

    victoire0 - here you go. This is a bit shorter. It is 100% manual coding though vs my previous example which was 100% UI driven.

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WSlTSAeMkIFaKjQUA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [#"012020" = _t, #"022020" = _t, #"032020" = _t, #"Other Column" = _t]),
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"012020", type text}, {"022020", type text}, {"032020", type text}}),
        OriginalName = 
            List.Select(
                Table.ColumnNames( #"Changed Type"), 
                each Text.End(_,4)="2020"
                ),
        NewName = 
            List.Transform(
                OriginalName, each "W" & Text.Start(_,2) 
                ),
        #"Dynamic Rename" = 
            Table.RenameColumns(
                #"Changed Type", 
                List.Zip({OriginalName, NewName})
                )
    in
        #"Dynamic Rename"

    Here is is by step:

    • Source and #Changed Type are just me keying in the same table as above example
    • OriginalName generates a list of the column names that ends in 2020. You would need to change the List.Select here to fit your needs. My code will break in 2021. You could use something like this:
      • Text.Start(Text.End(_,4),3) = "202"
      • That will find all columns that end in 202x. This code will break Jan 1, 2030.
    • NewName uses a "W" and adds the first two chars of the columns from the OriginalName list.
    • DynamicRename uses Table.RenameColumns and uses List.ZIp to use the lists above for the rename. List.Zip returns the following list of lists in memory.
      •  

      • So 012020 is paired with W01, 022020 is paired with W02, etc. So rename 012020 to W01. Same as this:
        • Table.RenameColumns(#"Changed Type",{{"012020", "W01"}})

    Hopefully that gets you started.