Forum Discussion
Renaming Columns by Column Number
- 9 years ago
This function renames columns based on their position.
The second and third argument are lists, each with the same number of elements.
ColumnNumbers is 0-based, so the first column is 0.
let RenameColumns = (InputTable as table, ColumnNumbers as list, NewColumnNames as list) => let OldColumnNames = Table.ColumnNames(InputTable), Indexed = List.Zip({OldColumnNames, {0..-1+List.Count(OldColumnNames)}}), Filtered = List.Select(Indexed, each List.Contains(ColumnNumbers,_{1})), IndexRemoved = List.Transform(Filtered, each _{0}), RenameList = List.Zip({IndexRemoved,NewColumnNames}), RenamedColumns = Table.RenameColumns(InputTable, RenameList) in RenamedColumns in RenameColumns
This function renames columns based on their position.
The second and third argument are lists, each with the same number of elements.
ColumnNumbers is 0-based, so the first column is 0.
let
RenameColumns = (InputTable as table, ColumnNumbers as list, NewColumnNames as list) =>
let
OldColumnNames = Table.ColumnNames(InputTable),
Indexed = List.Zip({OldColumnNames, {0..-1+List.Count(OldColumnNames)}}),
Filtered = List.Select(Indexed, each List.Contains(ColumnNumbers,_{1})),
IndexRemoved = List.Transform(Filtered, each _{0}),
RenameList = List.Zip({IndexRemoved,NewColumnNames}),
RenamedColumns = Table.RenameColumns(InputTable, RenameList)
in
RenamedColumns
in
RenameColumnsThank you so much MarcelBeug !!!
We struggle a bit to apply the function so we thought of adding an example.
1. Create a blank query and copy paste the whole function in the advanced editor (-> the new query will have the name of Query1)
2. In your query (the one you're working in), you can add a line similar to the below :
#"Rename Colum" = Query1(#"Promoted Headers", {2}, {"Date"}),
In this example:
- "Rename Column" is the new code line
- "Query1" is the new function created
- "Promoted Headers" is our previous line code
- "2" is the third column of our table
- "Date" is the new name of column