Skip to content

Renaming columns

Renaming columns makes data easier to read, so it is one of the most common preparation steps. A rename step refers to the old column names, though, so if the source renames a column, the step fails on the next refresh.

Where the columns stay in the same place but their names may change, it is safer to rename them by position. A small function makes that easy to repeat.

This function, named fnRenameColumnsByIndices, takes a table, a list of new names and a list of column positions, and renames the columns at those positions:

let
Source = (Source as table, ColumnNamesNew as list, Indices as list) =>
let
ColumnNamesOld = List.Transform( Indices, each Table.ColumnNames(Source){_} ),
ZippedList = List.Zip( { ColumnNamesOld, ColumnNamesNew } ),
#"Renamed Columns" = Table.RenameColumns( Source, ZippedList )
in
#"Renamed Columns"
in
Source

It works in three steps:

  1. ColumnNamesOld looks up the current name of the column at each position.
  2. List.Zip pairs each old name with its new name, which gives a list of {old, new} pairs.
  3. Table.RenameColumns applies those pairs to the table.

Take this table:

An Excel table with columns Date, Color, Supplier, City, Category and Revenue

The aim is to rename the fourth, fifth and sixth columns, which sit at positions 3 to 5 when counting from 0, to Data 1, Data 2 and Data 3. One way is to write out each pair by hand:

= Table.RenameColumns(Source,
{
{Table.ColumnNames(Source){3}, "Data 1"},
{Table.ColumnNames(Source){4}, "Data 2"},
{Table.ColumnNames(Source){5}, "Data 3"}
}
)

The function does the same with less repetition. Here List.Transform builds the new names from the numbers 1 to 3, and {3..5} gives the positions:

= fnRenameColumnsByIndices (
Source,
List.Transform (
{1..3},
each "Data " & Text.From(_)
),
{3..5}
)

Neither version mentions an existing column name, so the result is the same whatever the source calls those columns:

The table with the last three columns renamed Data 1, Data 2 and Data 3

Table.TransformColumnNames takes a different approach: it applies a function to every column name, such as one that trims spaces or changes the case. Because it works on whatever names it finds, it keeps working when the columns are reordered, which can make it the better choice where a rule rather than a fixed list describes the new names.

The technique on this page follows one in Gil Raviv’s Collect, Combine, and Transform Data Using Power Query in Excel and Power BI (Microsoft Press).