Cleaning Data with Power Query

Cleaning Data with Power Query – DataScienceWay tutorial

If you spend time every week fixing the same spreadsheet – trimming spaces, splitting columns, deleting junk rows, correcting dates – Power Query can do that work for you. It records each cleaning step once, then repeats all of them whenever you click Refresh. It is built into Excel (Data tab) and Power BI Desktop, and you do not need to write any code to use it.

This tutorial walks through cleaning a typical messy export with Power Query in Excel for Microsoft 365: importing, fixing headers, trimming text, correcting data types (including UK dates), splitting columns, removing duplicates, unpivoting, combining files and loading the result. The same steps work in Power BI, where the editor is almost identical.

What Power Query is (and isn’t)

Power Query is a data-preparation tool. You connect to a source (a workbook, CSV, folder, database or web page), apply transformation steps in the Power Query Editor, and load a clean table back into Excel or Power BI. The original source is never modified. Each step is stored in a language called M, which Power Query writes for you; you can read and edit it if you want, but it is not required.

It is not a replacement for formulas in every situation. Use it for repeatable shaping and cleaning of data before analysis; use formulas and pivot tables for the analysis itself.

The sample problem

Imagine a monthly export that looks like this, starting with two junk lines:

Sales export - generated by system
Run date: 01/04/2024
Order ID,Customer,Region,Order Date,Jan,Feb,Mar
A-001,"  smith, john ",north,05/01/2024,120,0,80
A-002,"PATEL, ANITA",South,17/01/2024,90,45,
A-003,"  smith, john ",north,05/01/2024,120,0,80
A-004,"Jones, Ben",south ,28/02/2024,0,210,60

Problems: junk rows at the top, names in “Surname, First” order with stray spaces and mixed case, inconsistent region capitalisation, UK dates, a duplicate order, a blank value, and months spread across columns instead of in one column. Because the names contain commas, they are wrapped in double quotes, which is how a correctly formed CSV handles this. Save it as sales_export.csv to follow along.

Step 1: Import the file

  1. In Excel, go to Data > Get Data > From File > From Text/CSV.
  2. Choose the file. A preview appears.
  3. Click Transform Data (not Load), which opens the Power Query Editor.

On the right, the Applied Steps pane lists every step. Click any step to see the data as it was at that point. This is your audit trail and undo history in one.

Flow of Power Query applied steps: Source, Removed Top Rows, Promoted Headers, Trimmed Text, Split Column, Changed Type with en-GB locale, Unpivoted Columns
The Applied Steps list is a repeatable recipe, not a one-off edit.

Step 2: Remove junk rows and promote headers

  1. Home > Remove Rows > Remove Top Rows, enter 2.
  2. Home > Use First Row as Headers (Transform tab in some versions).

If Power Query has already added a “Promoted Headers” or “Changed Type” step based on the junk rows, delete those steps (click the X beside them) before removing the top rows, so that types are set on the correct data later.

Step 3: Trim and fix text

  1. Select the Customer and Region columns (Ctrl+click headers).
  2. Transform > Format > Trim removes leading and trailing spaces.
  3. Transform > Format > Clean removes non-printing characters, which often come from system exports.
  4. With Region selected, Transform > Format > Capitalize Each Word, so “north”, “North” and “NORTH” all become “North”.

Power Query is case-sensitive in many operations, including filters, merges and removing duplicates. Standardising case early prevents “South” and “south” being treated as different values.

Step 4: Split and reorder names

  1. Select Customer, then Transform > Split Column > By Delimiter, choose Comma, split at the left-most delimiter.
  2. Rename the new columns to Surname and First Name (double-click a header).
  3. Trim both again (the space after the comma remains) and apply Capitalize Each Word.
  4. To create a full name, select First Name then Surname, and use Add Column > Merge Columns with a space as separator.

Step 5: Set data types – carefully with UK dates

Data types matter: text that looks like a number will not sum, and text dates cannot be grouped by month. Click the icon to the left of each column header to set its type.

For dates, the safest method is right-click the column > Change Type > Using Locale, choose Date and the locale English (United Kingdom). This guarantees that 05/01/2024 is read as 5 January, whatever regional settings the next person to refresh the file has on their computer. Without a locale, conversion depends on the machine’s settings, which is a common cause of files that work for one person and break for another.

Set Jan, Feb and Mar to Whole Number or Decimal Number. Any value that cannot be converted shows as Error; use Home > Keep Rows > Keep Errors on a duplicate query to inspect them rather than removing them blindly.

Step 6: Replace blanks and remove duplicates

  1. Select the month columns, Transform > Replace Values, replace null with 0 – but only if a blank genuinely means zero in your data.
  2. Select Order ID, then Home > Remove Rows > Remove Duplicates.

Selecting only Order ID means duplicates are judged on that key alone. If you select all columns, a row is a duplicate only if every value matches. Choose deliberately, and remove duplicates after trimming and fixing case, since “ smith” and “Smith” are not duplicates until cleaned.

Step 7: Unpivot months into rows

Data with one column per month is easy to read but awkward to analyse: you cannot easily filter by month or chart a trend. Analysis tools prefer a “long” format with a Month column and a Value column.

Before and after tables: a wide table with stores as rows and Jan, Feb and Mar as columns becomes a long table with Store, Month and Sales columns, one row per store and month
Unpivoting turns a report layout into analysis-ready data (illustrative figures).
  1. Select the columns that identify each row (Order ID, Full Name, Region, Order Date).
  2. Transform > Unpivot Columns > Unpivot Other Columns.
  3. Rename Attribute to Month and Value to Amount.

Using “Unpivot Other Columns” is more robust than selecting the month columns: when April appears in next month’s export, it is included automatically.

Step 8: Load the result

Home > Close & Load loads the result as a new Excel Table. Use Close & Load To… to load to the Data Model or create a connection only (useful for intermediate queries). Next month, replace the CSV with the new export (same name and location) and click Data > Refresh All. Every step runs again in seconds.

Step 9: Look at the M code

Open Home > Advanced Editor to see what Power Query recorded. A simplified version of our steps looks like this:

let
    Source   = Csv.Document(File.Contents("C:\Data\sales_export.csv"), [Delimiter=",", QuoteStyle=QuoteStyle.Csv]),
    Skipped  = Table.Skip(Source, 2),
    Headers  = Table.PromoteHeaders(Skipped, [PromoteAllScalars=true]),
    Trimmed  = Table.TransformColumns(Headers, {{"Customer", Text.Trim}, {"Region", Text.Trim}}),
    Proper   = Table.TransformColumns(Trimmed, {{"Region", Text.Proper}}),
    Typed    = Table.TransformColumnTypes(Proper, {{"Order Date", type date}}, "en-GB"),
    Deduped  = Table.Distinct(Typed, {"Order ID"}),
    Unpivot  = Table.UnpivotOtherColumns(Deduped, {"Order ID", "Customer", "Region", "Order Date"}, "Month", "Amount")
in
    Unpivot

Each line is one applied step, and each step refers to the previous one. Notice the "en-GB" culture argument from the “Using Locale” type change. Reading M is a good way to understand exactly what a query does, and small edits (such as changing a file path) are often quicker here than in the interface.

Step 10: Combine many files from a folder

If you receive one file per month, Power Query can combine them all. Put the files in one folder, then Data > Get Data > From File > From Folder, choose the folder and click Combine & Transform Data. Power Query builds a sample transformation from one file and applies it to all of them. Drop a new file into the folder and refresh to include it. The files must share the same structure.

Common mistakes

  • Changing types before removing junk rows, which creates errors or wrong types.
  • Converting dates without a locale, so results depend on each user’s PC settings.
  • Removing errors without looking at them. They often reveal real data problems.
  • Removing duplicates before trimming and fixing case.
  • Hard-coded file paths on a personal drive, which break for colleagues. Use a shared location or a parameter.
  • Replacing nulls with zero when a blank means “unknown”.
  • Selecting columns to unpivot instead of “Unpivot Other Columns”, so new months are missed.

FAQ

Is Power Query available on Mac?

Yes, in Microsoft 365 for Mac, although historically with fewer connectors than Windows. Check your version’s Get Data menu.

Does Power Query change my source file?

No. It only reads the source and loads a cleaned copy.

Power Query or Python?

Power Query is excellent for repeatable cleaning inside Excel and Power BI, with no code. Python is more flexible for complex logic, large data and automation. Compare them in Excel vs Python and see the Python version in Cleaning Messy Data with Pandas.

Why is my refresh slow?

Common causes are many files in a folder query, merges with large tables, and steps that prevent “query folding” to a database. Remove unneeded columns and rows as early as possible.

Next steps

Summarise your clean table with Excel Pivot Tables, look up values with XLOOKUP, and build interactive reports in Power BI.

LJ

About the author: Lucky Joseph

Lucky is a UK-based writer with a data science background who runs DataScienceWay. Every tutorial is tested before publication; if you spot something that no longer works, please get in touch.

More about DataScienceWay · Contact