Forum Discussion
how to dynamically replace values for multiple columns
- 6 months ago
Hello vc25,
You can dynamically replace values in all columns that start with "mt" by using a lookup mapping and Table.TransformColumns.
Step 1 – Create a mapping table
Create a small table with your replacements and load it into Power Query, for example call it StateMap:
Code | State
1 Georgia
2 Alabama
3 Texas
4 Florida
Step 2 – Use this M code in your main query
let
Source = YourPreviousStep,
// Get all columns that start with "mt"
MtColumns = List.Select(
Table.ColumnNames(Source),
each Text.StartsWith(_, "mt")
),
// Convert mapping table to record
MapRecord = Record.FromTable(
Table.TransformColumnTypes(StateMap, {{"Code", type text}})
),
// Replace values dynamically
Replaced = Table.TransformColumns(
Source,
List.Transform(
MtColumns,
(col) => {
col,
each Record.FieldOrDefault(MapRecord, Text.From(_), _),
type text
}
)
)
in
Replaced
Why this works
It automatically finds all columns named mt1, mt2, mt3, etc.
It replaces their numeric values using the mapping table.
It works even if the number of mt columns changes.
Everything is done in one single step, no hardcoding.
This is the standard scalable pattern for dynamic value replacement in Power Query.
does the statemap query need to be text or number data type? my "mt" columns are text type.
- Olufemi76 months agoSuper User
Hello vc25,
Good question. StateMap[Code] should be Text, since your mt columns are also Text.
In the solution, this line is the key: Record.FieldOrDefault(MapRecord, Text.From(_), _)
Because Text.From(_) is used, the lookup is done using text values. That’s why the mapping table is explicitly converted here:
MapRecord = Record.FromTable(
Table.TransformColumnTypes(StateMap, {{"Code", type text}})
)As long as both the mt column values and StateMap[Code] are text, the replacement will work correctly and scale as columns are added or removed.
Microsoft docs (reference):
Table.TransformColumns
https://learn.microsoft.com/powerquery-m/table-transformcolumnsRecord.FromTable
https://learn.microsoft.com/powerquery-m/record-fromtableRecord.FieldOrDefault
https://learn.microsoft.com/powerquery-m/record-fieldordefault
Hope that clarifies it
- vc256 months agoHelper I
I keep getting this error.
mapping table called "fishnames"