Sub topic 6
Cleaning text: trim, clean, case, and replace values
This chapter assumes you can open the Power Query Editor, that you know what Applied Steps are, and that you have already set data types on your columns. If any of that is unfamiliar, review the earlier chapters on the editor and on data types first.
Text columns cause many of the problems that make a lookup or a join fail. Two values that look the same on screen can differ by a trailing space, a hidden character, or a capital letter. Power Query treats them as different values. This chapter shows how to find those differences and remove them.
Why text that looks equal is not equal
Power Query compares text exactly. It is case-sensitive by default, and it counts every character, including spaces and characters you cannot see.
| Value in the cell | What is wrong | Effect |
|---|---|---|
| `North ` | Trailing space | Does not match `North` in a merge |
| `north` | Different case | Does not match `North` in a merge or Remove Duplicates |
| `No` + line break + `rth` | Non-printing character | Looks odd or breaks across lines |
| `North` with a non-breaking space | Space that Trim does not remove | Survives a plain Trim |
Cleaning these values before you merge, group, or remove duplicates is the usual order of work. A Group By on an uncleaned Region column would give you separate rows for North and North .
The four main transforms
The Transform tab on the Home or Transform ribbon has a Format menu. Select the column first, then choose one of these commands.
- Trim removes leading and trailing spaces. It does not touch spaces between words.
- Clean removes non-printing characters, such as line breaks and tab characters, that come from the first 32 characters of the ASCII set.
- Lowercase, UPPERCASE, and Capitalize Each Word change case.
- Replace Values swaps one value for another.
Each command adds an Applied Step and writes an M function behind it. The functions are Text.Trim, Text.Clean, Text.Lower, Text.Upper, and Text.Proper.
Trim and Clean together
Trim and Clean solve different problems, so you often need both. In the ribbon you apply them as two steps. In M you can combine them in one step, as the first code example in this tutorial does:
let
Source = Excel.CurrentWorkbook(){[Name="SalesRaw"]}[Content],
Typed = Table.TransformColumnTypes(Source, {{"Date", type date}, {"Amount", type number}}),
Trimmed = Table.TransformColumns(Typed, {{"Region", each Text.Trim(Text.Clean(_)), type text}})
in
TrimmedRead the key line from the inside out. Text.Clean(_) removes non-printing characters from the current value, which _ stands for. Text.Trim then removes the outer spaces. The each keyword runs the expression once for every row. The final type text keeps the column typed as text.
The order matters in one case. If a value ends with a line break after a space, Clean first leaves a trailing space that Trim then removes. If you trim first, the line break blocks Trim from reaching the space.
Changing case
Use case changes to make values comparable.
- Use lowercase or UPPERCASE for codes, such as product IDs or country codes, where you want a single standard form.
- Use Capitalize Each Word for names and places.
Text.Propercapitalizes the first letter of each word and lowercases the rest. It turnsmcdonaldintoMcdonaldandUSAintoUsa, so check the result before you keep it.
Case changes also affect Remove Duplicates, which is case-sensitive. Smith and SMITH count as two different rows until you standardize the case.
Replacing values
Replace Values is under Transform on the ribbon, and you can also right-click a column header. It opens a dialog with two boxes, Value To Find and Replace With.
Keep these behaviors in mind:
- The match is case-sensitive unless you open Advanced options. Replacing
n/adoes not changeN/A. - By default it replaces any cell part that matches, not only whole cells. Replacing
StwithStreetwould also change the start ofStone. - The Match entire cell contents option in Advanced options limits the change to cells that equal the search value.
- Replace Values works on the selected column only. Select several columns first to apply the same replacement to each.
To replace a placeholder with a real null, enter null in the Replace With box. Power Query reads it as a null value and not as the word. To replace nulls with a value, type null in Value To Find. The next chapters cover nulls in more detail.
Replace with a function
The Replace Values dialog creates Table.ReplaceValue. The Replacer.ReplaceText argument matches parts of a string. Replacer.ReplaceValue matches whole values.
let
Source = Excel.CurrentWorkbook(){[Name="SalesRaw"]}[Content],
Whole = Table.ReplaceValue(Source, "N/A", null, Replacer.ReplaceValue, {"Region"}),
Part = Table.ReplaceValue(Whole, "St.", "Street", Replacer.ReplaceText, {"Address"})
in
PartThis query turns every N/A cell in Region into null, then replaces the text St. with Street inside Address. The dialog produces the same thing when you choose the matching options.
A repeatable cleaning order
A consistent order keeps results predictable.
- Set the data type to Text for columns you plan to clean.
- Apply Clean, then Trim.
- Standardize the case.
- Replace known bad values, such as
N/A,-, or misspellings. - Only then remove duplicates, merge, or group.
Common problems
Trim leaves a gap that still shows
Text copied from web pages often contains a non-breaking space, character code 160. Trim and Clean ignore it. Use Replace Values and paste that character in Value To Find, or use M with Character.FromNumber(160):
let
Source = Excel.CurrentWorkbook(){[Name="SalesRaw"]}[Content],
NoNbsp = Table.ReplaceValue(Source, Character.FromNumber(160), " ", Replacer.ReplaceText, {"Region"}),
Trimmed = Table.TransformColumns(NoNbsp, {{"Region", each Text.Trim(Text.Clean(_)), type text}})
in
TrimmedThe first step turns each non-breaking space into an ordinary space. The second step then trims it.
Double spaces inside a value
Trim in Power Query removes only the outer spaces. Unlike the Excel TRIM function, it does not shrink repeated spaces inside the text. To collapse them, use a custom step that splits on spaces, removes empty parts, and joins the rest:
let
Source = Excel.CurrentWorkbook(){[Name="SalesRaw"]}[Content],
OneSpace = Table.TransformColumns(Source, {{"Region", each Text.Combine(List.Select(Text.Split(_, " "), each _ <> ""), " "), type text}})
in
OneSpaceThis fails on a null cell because Text.Split needs text. Fill or replace the nulls first, or guard the step with an if _ = null then null else ... test.
Case-insensitive replacement
Replace Values has no case option. Convert the column to one case first, then replace using that case. Alternatively, use Replacer.ReplaceText inside Table.TransformColumns with Text.Replace after lowercasing.
Cleaning many columns at once
Select several columns with Ctrl+click, then apply Trim. Power Query writes one step that covers all of them. This is faster than one step per column and keeps the Applied Steps list short.
Check your work
After cleaning, confirm the result before moving on. Turn on Column quality and Column distribution under the View tab. Column distribution shows the count of distinct and unique values. If a Region column should have four values and shows six, some text still differs. Open the column's filter dropdown to see the remaining variants.
Exercise
A Region column contains North, north , and NORTH. You want Group By to produce one row for North. Which steps do you apply, and in what order? Why is Trim alone not enough?
Show answer
Apply Clean, Trim, and then a case change such as Capitalize Each Word, then run Group By. Trim removes only the trailing space in north , so the three values would still differ by case. Group By compares text exactly, so the case change is needed to make all three values identical.
Exercise
After you trim a column, the filter dropdown still lists two entries that look like Berlin. Name one likely cause and one way to fix it.
Show answer
One entry probably contains a non-breaking space (character code 160), which Trim ignores. Use Replace Values with Character.FromNumber(160) or the pasted character to turn it into a normal space, then trim again.
Exercise
You use Replace Values to change St to Street in an Address column and Stone Road becomes Streetone Road. What setting prevents this, and does it suit this task?
Show answer
Turn on Match entire cell contents in Advanced options. It would only replace cells that equal St, so it does not suit this task, which needs part of a cell replaced. A better fix is to search for St. or St with surrounding characters, or to handle the word with a more specific replacement.