Converting Type in Power Query - M PDF
Converting Type in Power Query - M PDF
DID YOU
KNOW?
Introduction
In the first part, we talked about ascribing data types - defining a
column's data type without conversion or type check (until runtime).
Now, we'll explore retaining data types and type conversion in M.
Here's a pro tip: if you make "Change Type" the final step in your query,
you can limit the number of steps required. Most users don't do this
because Table.TransformColumnTypes doesn't have a MissingField.Type
parameter causing the query to break when a column doesn't exist.
Let's find out how and where we can retain type to reduce steps and
explore different methods to convert type.
Losing type after invoking Table.ReplaceValue
When using Transform/ Replace Values you can match entire cell content
using Replacer.ReplaceValue or look for each occurrence of the oldValue
in a cell with Replacer.ReplaceText. The former will return type any,
the latter can retain a declared type text, as shown here.
Above type text reverts to type any. While below, type text is retained.
Using the user interface for this transformation generates a list with
typeTransformation lists in the following format:
{column name, type name}
https://learn.microsoft.com/en-us/power-query/data-types#data-type-conversion-matrix
Leverage a naming convention to set type.
To make the "Change Type" step less error-prone, avoid hard-coding
column names. Instead, leverage your naming convention for more
precise results.
Table.TransformColumnTypes( PrevStepName,
List.Transform(
List.Select( Table.ColumnNames(PrevStepName),
each Text.EndsWith( _, " PCT", Comparer.OrdinalIgnoreCase)
), (x)=> {x, Percentage.Type}
)
)
The code above will convert all columns in the table where the column
name ends with "PCT" (ignoring case) to a Percentage.Type.
You can use the combination operator (&) to add more sets.
Above we're starting with a list of column names and transform each
name into a transformOperations list with this format:
{ column name, transformation, new column type }
It's important to understand that there are always two types at play:
value-type and column-type. Until column-type is set, you are dealing with
the value-type. A column with numeric values may be of a text type,
leading to errors in calculations that require a number type. To avoid
these errors, use one of the conversion functions, listed here:
https://learn.microsoft.com/en-us/powerquery-m/type-conversion
Keep in mind that dealing with data types in Power Query requires
careful attention and knowledge. By following these tips and tricks,
you can work with data types like a pro.
Like my content?
Consider a connection,
following me or #pqtodaysmenu
I LOVE SOLVING
PRACTICAL PROBLEMS
WITH POWER QUERY/ M.