Power Query course · Lesson 4 of 17

Cleaning text and numbers in Power Query

Trim, clean, change case, replace values, extract parts of text, convert text to numbers with the right locale and fix errors, all as repeatable steps.

Beginner 16 min read

Dirty text and numbers stored as text are the most common reasons a lookup fails or a total looks wrong. In a worksheet you would fix them with helper columns using TRIM, CLEAN, PROPER, SUBSTITUTE and VALUE. Power Query has an equivalent for each, but it applies the fix to the whole column as a step, so next month's export gets exactly the same treatment. This lesson works through a customer export and a bank statement.

The sample: a messy customer export

ABCD
1Cust IDCustomerCountryCredit limit
2c-0091 hellas olive oil greece15,000 EUR
3C-0092NORDLICHT GMBHGermany 8,500 EUR
4c-0093Atlantic TilesPORTUGALn/a
5C-0094baltic amber ltd.latvia12,250 EUR

Before: leading and trailing spaces, double spaces inside names, mixed case, a currency word inside the number, and a text placeholder in a numeric column.

Format: Trim, Clean and case

Select the text columns you want to fix (hold Ctrl [Cmd on Mac] to select several headers), then choose Transform › Format and one of these commands. The same list is available by right-clicking a header and choosing Transform.

CommandWhat it doesExcel equivalent
lowercasehellas olive oilLOWER
UPPERCASEHELLAS OLIVE OILUPPER
Capitalize Each WordHellas Olive OilPROPER
TrimRemoves leading and trailing whitespaceTRIM (partly)
CleanRemoves non-printable characters such as line breaksCLEAN
Add Prefix / Add SuffixAdds fixed text before or after each value&
Watch out. Power Query's Trim is not the same as Excel's TRIM. Excel's TRIM also reduces double spaces inside the text to single spaces; Power Query's Trim only removes spaces at the start and end. NORDLICHT GMBH keeps its double space after Trim.

To collapse inner double spaces, use Transform › Replace Values, enter two spaces in Value To Find and one space in Replace With. If there might be three or more spaces, a more robust approach is a custom step that splits on spaces, drops the empty pieces and joins the rest again:

Power Query M
= Table.TransformColumns(#"Trimmed Text", {{"Customer", each Text.Combine(List.Select(Text.Split(_, " "), each _ <> ""), " "), type text}})
Split into words, keep the non-empty ones, join with single spaces. This is the exact behaviour of Excel's TRIM.
Tip. Customer IDs like c-0091 and C-0092 look the same to a person but not to Power Query, which compares text case-sensitively. Apply Format › UPPERCASE to key columns before you merge or remove duplicates, otherwise matches will be missed.

Replace Values

Transform › Replace Values (also on Home, and on the right-click menu) replaces a piece of text everywhere in the selected columns. For our credit limits, replace EUR (with a leading space) by nothing: leave Replace With empty. Click Advanced options to see two more settings:

  • Match entire cell contents: replace only cells whose whole value equals the search text, so n/a is replaced but a note such as n/a until approval is not. To turn the placeholder into a real empty value, run the replacement and then check the formula bar: the replacement must be the keyword null without quotes, as in the code below.
  • Replace using special characters: insert a tab, carriage return, line feed or non-breaking space into the search box. Web data often contains non-breaking spaces (character 160) that Trim does not remove; this is how you find them.
Power Query M
= Table.ReplaceValue(#"Uppercased Text", "n/a", null, Replacer.ReplaceValue, {"Credit limit"})
Replacer.ReplaceValue swaps whole values; the UI writes Replacer.ReplaceText when you replace part of the text. Typing null without quotes in the formula bar gives a real null.

Converting text to numbers

After removing EUR, Credit limit still contains text like 15,000. Click the type icon and choose Whole Number or Decimal Number. Whether the comma is read as a thousands separator depends on your computer's regional settings, which is why a query that works on your PC may fail on a colleague's. The safe way is Change Type › Using Locale… with the locale of the source: English (United States) for 15,000.50, German (Germany) for 15.000,50.

ABCD
1Cust IDCustomerCountryCredit limit
2C-0091Hellas Olive OilGreece15000
3C-0092Nordlicht GmbhGermany8500
4C-0093Atlantic TilesPortugalnull
5C-0094Baltic Amber Ltd.Latvia12250

After: IDs uppercased, names trimmed with inner spaces collapsed and capitalised, countries fixed, credit limits real numbers and the placeholder turned into null.

Notice Nordlicht Gmbh: Capitalize Each Word does not know that GmbH is written with a capital H. Fix such known exceptions with one more Replace Values step (Gmbh → GmbH, with Match entire cell contents off).

A bank statement: signs, brackets and debit/credit

ABC
1Booking dateTextAmount
22026-03-02Card payment FUEL STATION(64.90)
32026-03-03Transfer IN Acme Payroll2,410.00
42026-03-04Standing order RENT(850.00)
52026-03-05Card payment PHARMACY(18.35)

Before: accounting-style negatives in brackets, thousands separators and a description with inner double spaces.

  1. Select Amount and choose Transform › Replace Values: replace ( with -.
  2. Replace Values again: replace ) with nothing.
  3. Right-click the header › Change Type › Using Locale…, choose Decimal Number and English (United States).
  4. Select Text, then Transform › Format › Trim, and collapse the double spaces as above.
  5. Add a direction column: Add Column › Conditional Column, name Direction, if Amount is less than 0 then Out, else In (more in Custom and conditional columns).
ABCD
1Booking dateTextAmountDirection
22026-03-02Card payment FUEL STATION-64.9Out
32026-03-03Transfer IN Acme Payroll2410In
42026-03-04Standing order RENT-850Out
52026-03-05Card payment PHARMACY-18.35Out

After: signed decimal numbers that can be summed, and a clean description.

Extract: pieces of text

Transform › Extract (or Add Column › Extract to keep the original) pulls part of a text value:

  • Length: number of characters, handy to find IBANs or postcodes with the wrong length.
  • First Characters / Last Characters: like LEFT and RIGHT. Last Characters 4 on a card description gets the last four digits.
  • Range: a starting index (counted from 0, not 1) and a number of characters, like MID.
  • Text Before Delimiter, Text After Delimiter, Text Between Delimiters: like TEXTBEFORE and TEXTAFTER, with options to scan from the end or skip delimiters. Text Before Delimiter with on Card payment FUEL STATION returns Card.
Power Query M
= Table.AddColumn(#"Changed Type with Locale", "Merchant", each Text.AfterDelimiter([Text], "payment "), type text)
Extract the merchant name after the word payment. Rows without that word return an empty text.

Column From Examples

When you are not sure which command produces what you want, choose Add Column › Column From Examples › From Selection. Type the result you expect for the first one or two rows (for example FUEL STATION next to Card payment FUEL STATION) and Power Query proposes a formula, shown above the preview. Press OK and it becomes a normal step whose M you can read in the formula bar. It is Flash Fill, but repeatable.

Numbers: rounding and arithmetic

With a numeric column selected, the Transform tab offers Standard (Add, Multiply, Subtract, Divide, Integer-Divide, Modulo, Percentage, Percent Of), Scientific (Absolute Value, Power, Square Root…), Rounding (Round Up, Round Down, Round…) and Information (Is Even, Is Odd, Sign). Converting cents to euros is Standard › Divide by 100; showing every amount as positive is Scientific › Absolute Value.

Note. Power Query's Round uses banker's rounding by default (2.5 becomes 2, 3.5 becomes 4), unlike Excel's ROUND. If you need Excel-style rounding, edit the step to Number.Round(_, 2, RoundingMode.AwayFromZero).

Dealing with errors

If a value still cannot be converted, the cell shows Error. Use Home › Keep Rows › Keep Errors temporarily to see only the problem rows and understand them. Then either fix the cause with Replace Values, or use Transform › Replace Errors to put a default value such as 0 or null. Avoid Remove Rows › Remove Errors on money columns: deleting a row because its amount was badly typed silently changes your totals.

Check yourself

1. A name contains two spaces in the middle. What does Power Query's Trim do?

2. Why uppercase customer IDs before a merge?

3. Amounts look like 1.250,00. Which conversion is safest?

4. Which Extract option counts from position 0?

5. A few amounts fail to convert. Which approach keeps totals honest?