Sub topic 5
Promoting headers and removing unwanted rows and duplicates
This chapter assumes you can open the Power Query Editor, read the Applied Steps pane, and set data types as covered in the previous chapters. You should also be comfortable with Excel tables and CSV files.
Imported data rarely arrives ready to use. Report exports put titles above the real column names. Files end with "Total" rows. The same record appears twice because two systems both exported it. This chapter covers the operations that fix these problems: promoting headers, removing rows by position and by content, and removing duplicates.
Why the order of steps matters
Each operation you apply becomes a step, and each step works on the output of the step before it. If you remove rows before the header is promoted, you are working with generic column names such as Column1. If you promote headers first, the wrong row may become the header. Plan the sequence before you click.
A reliable order for messy files is:
- Remove the top rows that are not data (titles, notes, blank lines).
- Promote the first remaining row to headers.
- Set data types.
- Remove blank rows, total rows, and error rows.
- Remove duplicates.
Setting types before removing duplicates matters because Power Query compares values using their type. Text such as "100" and the number 100 are different values.
Promoting headers
When Power Query imports a CSV file or a range, it often guesses that the first row holds the column names and promotes it automatically. Excel tables already carry their headers, so no promotion is needed. When the guess is wrong, you see columns named Column1, Column2, and so on, with the real names sitting in the first data row.
To promote headers, select Transform > Use First Row as Headers. The matching M function is Table.PromoteHeaders. The reverse operation, Use Headers as First Row, calls Table.DemoteHeaders. Use it when automatic promotion took the wrong row, then remove the unwanted rows and promote again.
This query imports a CSV file and promotes its headers:
let
Source = Csv.Document(File.Contents("C:\Data\sales.csv"), [Delimiter=",", Encoding=65001, QuoteStyle=QuoteStyle.Csv]),
Promoted = Table.PromoteHeaders(Source, [PromoteAllScalars=true]),
Typed = Table.TransformColumnTypes(Promoted, {{"OrderID", Int64.Type}, {"Amount", type number}})
in
TypedThe option PromoteAllScalars=true tells Power Query to convert every header value to text. Without it, a numeric header such as the year 2025 is not promoted as text and the column keeps a generic name. Include the option when your headers may contain numbers or dates.
Header gotchas
- Duplicate header names. Power Query requires unique column names. If two headers are both
Amount, the second becomesAmount_1(or similar). Rename the columns afterward so the meaning is clear. - Blank header cells. An empty header cell becomes a name such as
Column3. Rename it or remove the column. - Type step already inserted. After promoting headers, Power Query often adds a Changed Type step automatically. If you later insert a step before the promotion, that type step refers to column names that may no longer exist, and the query shows an error such as "The column 'OrderID' of the table wasn't found."
- Headers that change. A type step written with fixed column names breaks when the source renames a column. Check the step if a refresh fails after the source layout changes.
Removing unwanted rows
The Home > Remove Rows menu offers several choices. Each one answers a different question.
| Command | What it removes | M function |
|---|---|---|
| Remove Top Rows | The first N rows | `Table.Skip` |
| Remove Bottom Rows | The last N rows | `Table.RemoveLastN` |
| Remove Alternate Rows | A repeating pattern of rows | `Table.AlternateRows` |
| Remove Blank Rows | Rows where every column is empty or null | `Table.SelectRows` |
| Remove Errors | Rows with an error in selected columns | `Table.RemoveRowsWithErrors` |
| Filter by a value | Rows that match a condition you choose | `Table.SelectRows` |
Removing by position
Remove Top Rows and Remove Bottom Rows depend on a fixed count. If next month's export has three title lines instead of two, the step removes the wrong rows. Use position-based removal only when the file layout is stable. When it is not, filter by content instead.
Removing by content
To remove total rows, use the filter arrow on a column and clear the check box for Total, or choose Text Filters > Does Not Equal. This works regardless of where the row sits. Filters are case sensitive, so Total and TOTAL are different values. Apply Transform > Format > Capitalize Each Word or Text.Upper first if the case varies, as covered in the text cleanup chapter.
Filtering also has a trap. The filter list shows only the first 1,000 distinct values by default. If a value you want to exclude is not shown, choose Load more in the list, or use Text Filters with a typed condition.
Blank cells may be null or may be empty strings that look blank. Remove Blank Rows removes rows where all cells are null or empty text. It does not remove a row where one cell is blank and the others have values. To remove those, filter the key column with Remove Empty. A cell containing only spaces is neither null nor empty, so trim the column first.
Removing duplicates
Select one or more columns and choose Home > Remove Rows > Remove Duplicates. Power Query keeps the first row for each distinct combination of values in the selected columns and removes later ones. The M function is Table.Distinct.
The columns you select define what counts as a duplicate:
- Select every column to remove only rows that are identical throughout.
- Select a key column such as
OrderIDto keep one row per order, even if other columns differ. - Select several columns to define a composite key, such as
CustomerIDandOrderDate.
The following query removes duplicate orders, keeping the first row for each OrderID:
let
Source = Excel.CurrentWorkbook(){[Name="SalesRaw"]}[Content],
Typed = Table.TransformColumnTypes(Source, {{"OrderID", Int64.Type}, {"Amount", type number}}),
Trimmed = Table.TransformColumns(Typed, {{"Region", each Text.Trim(Text.Clean(_)), type text}}),
Distinct = Table.Distinct(Trimmed, {"OrderID"})
in
DistinctDuplicate gotchas
- Case sensitivity.
Smithandsmithare different values, so both rows survive. Normalize case first. - Hidden whitespace.
"North"and"North "are different. Trim and clean text before removing duplicates. - Which row is kept. Power Query keeps the first occurrence in the current row order. To keep the newest record, sort descending by date first. Because a later step may be reordered by the engine in some sources, wrap the sorted table in
Table.Bufferwhen you need the order to be guaranteed. - Nulls. Rows with null in the selected key columns are treated as duplicates of each other. Filter them out first if that is not what you want.
- Types. A column holding
1as text in some rows and as a number in others should be converted to one type first.
let
Source = Excel.CurrentWorkbook(){[Name="SalesRaw"]}[Content],
Typed = Table.TransformColumnTypes(Source, {{"OrderID", Int64.Type}, {"Date", type date}}),
Sorted = Table.Sort(Typed, {{"Date", Order.Descending}}),
Buffered = Table.Buffer(Sorted),
Newest = Table.Distinct(Buffered, {"OrderID"})
in
NewestFinding duplicates instead of deleting them
Sometimes you must investigate duplicates before discarding them. Select the key column and choose Home > Keep Rows > Keep Duplicates to see only the repeated rows. This step is useful for auditing, and you can disable it or delete it once the check is done.
Checking your result
After cleaning, confirm the outcome rather than assuming it:
- Turn on View > Column quality and Column distribution to see empty and error counts per column.
- Turn on Column profiling based on entire data set from the status bar. By default, profiling covers only the first 1,000 rows.
- Compare the row count with the source. A large unexpected drop usually means a filter was too broad.
Summary of decisions
- Use position-based removal only for fixed layouts. Use content filters when layouts vary.
- Promote headers before setting types, and set types before removing duplicates.
- Trim, clean, and normalize case before comparing values.
- Choose the key columns for duplicate removal deliberately. They define what "duplicate" means.
Exercise
An export has two title lines above the column names, a "Total" row at the bottom, and some orders listed twice. Describe the steps you would apply, in order, and name one reason for that order.
Show answer
Remove Top Rows (2), then Use First Row as Headers, then set data types, then filter out the "Total" row (using a content filter rather than Remove Bottom Rows if the number of trailing rows can change), then trim the text columns, then Remove Duplicates on the OrderID column. Headers must be promoted after the title lines are removed, otherwise a title becomes the header. Types and trimming come before duplicate removal because values such as "100" versus 100, or "North" versus "North ", would otherwise be treated as different and the duplicates would survive.
Exercise
You need to keep only the most recent row for each OrderID, but Remove Duplicates keeps the first row it finds. How do you get the latest row, and why might you add Table.Buffer?
Show answer
Sort the table by the date column in descending order, then run Remove Duplicates on OrderID so the first row for each order is the newest one. Wrapping the sorted table in Table.Buffer stores it in memory and makes the sort order hold when the duplicate step runs, because some sources can otherwise reorder rows between steps.