Forum Discussion
Fromit87
3 years agoAdvocate I
Change column names based on a condition
Hi there, I have a table to transform to a certain layout. The end result should be that any column, that has (text)values in the rows starting with "L" should be renamed to Level 1, Level 2, L...
- 3 years ago
Hi,
GIVEN
WHEN
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content], // YOUR table here #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(Source, {"Merged.1"}, "Attribute", "Value"), #"Added Index" = Table.AddIndexColumn(#"Unpivoted Other Columns", "Index", 0, 1, Int64.Type), #"Added Custom" = Table.AddColumn(#"Added Index", "LevelColumnName", each if Text.StartsWith([Value], "L") then [Index] else null), OriginalLevelIndices = List.RemoveNulls(Table.Column(#"Added Custom", "LevelColumnName")), NewLevelIndices = List.Numbers(1, List.Count(OriginalLevelIndices)), TranslationTable = Table.FromColumns({NewLevelIndices,OriginalLevelIndices}), Final = List.Accumulate(Table.ToRows(TranslationTable), #"Added Custom", (t,r) => Table.ReplaceValue(t, r{1}, r{0}, Replacer.ReplaceValue, Table.ColumnNames(t))), #"Added Custom1" = Table.AddColumn(Final, "NewColumnNames", each if [LevelColumnName] <> null then "Level" & Text.From([LevelColumnName]) else [Attribute]), #"Removed Columns" = Table.RemoveColumns(#"Added Custom1",{"Attribute", "Index", "LevelColumnName"}), #"Pivoted Column" = Table.Pivot(#"Removed Columns", List.Distinct(#"Removed Columns"[NewColumnNames]), "NewColumnNames", "Value") in #"Pivoted Column"THEN the "level" columns should be renamed
Hope this helps.