Как заменить ошибки во всех столбцах power query

 

vitajlka

Пользователь

Сообщений: 15
Регистрация: 17.01.2018

Как заменить все ошибки в таблице сразу?
В источнике данных есть #ссылка или могут быть другие типы ошибок, соответственно при загрузке в модель данных query не даёт этого сделать из-за наличия ошибок. Хотя на последнем этапе в каждом столбце сделал замену ошибок, но это не помогает. В принципе, если я сделаю в самом начале в каждом столбце замену ошибок, то это сработает. Но столбцов и строк много, хочется найти быстрый способ
Текст запроса:
let
   Источник = Excel.Workbook(File.Contents(Excel.CurrentWorkbook(){[Name=»filepath»]}[Content]{0}[Путь]&»Пример1.xlsx»), null, true),
   данные_Sheet = Источник{[Item=»данные»,Kind=»Sheet»]}[Data],
   #»Удаленные столбцы» = Table.RemoveColumns(данные_Sheet,{«Column1», «Column2», «Column3»}),
   #»Удаленные верхние строки» = Table.Skip(#»Удаленные столбцы»,2),
   #»Транспонированная таблица» = Table.Transpose(#»Удаленные верхние строки»),
   #»Объединенные столбцы» = Table.CombineColumns(Table.TransformColumnTypes(#»Транспонированная таблица», {{«Column2», type text}}, «ru-RU»),{«Column1», «Column2»},Combiner.CombineTextByDelimiter(«:», QuoteStyle.None),»Сведено»),
   #»Транспонированная таблица1″ = Table.Transpose(#»Объединенные столбцы»),
   #»Повышенные заголовки» = Table.PromoteHeaders(#»Транспонированная таблица1″, [PromoteAllScalars=true]),
   #»Другие столбцы с отмененным свертыванием» = Table.UnpivotOtherColumns(#»Повышенные заголовки», {«:Фин счет»}, «Атрибут», «Значение»),
   #»Разделить столбец по разделителю» = Table.SplitColumn(#»Другие столбцы с отмененным свертыванием», «Атрибут», Splitter.SplitTextByDelimiter(«:», QuoteStyle.Csv), {«Атрибут.1», «Атрибут.2»}),
   #»Строки с примененным фильтром» = Table.SelectRows(#»Разделить столбец по разделителю», each ([Атрибут.1] = «бюджет» or [Атрибут.1] = «Прогноз» or [Атрибут.1] = «Факт»)),
   #»Замененные ошибки» = Table.ReplaceErrorValues(#»Строки с примененным фильтром», {{«Значение», 0}}),
   #»Замененные ошибки1″ = Table.ReplaceErrorValues(#»Замененные ошибки», {{«Атрибут.1», «0»}}),
   #»Замененные ошибки2″ = Table.ReplaceErrorValues(#»Замененные ошибки1″, {{«:Фин счет», 0}}),
   #»Замененные ошибки3″ = Table.ReplaceErrorValues(#»Замененные ошибки2″, {{«Атрибут.2», «0»}})
in
   #»Замененные ошибки3″

An Excel table as data source may contain error values (#NA, #DIV/0), which could disturbe later some steps during the transformation process in Power Query.
Depending of the following steps, we may get no output but an error. So how to handle this cases?

I found two standard steps in Power Query to catch them:

  • Remove errors (UI: Home/Remove Rows/Remove Errors) -> all rows with an error will be removed
  • Replace error values (UI: Transform/Replace Errors) -> the columns have first to be selected for performing this operations.

The first possibility is not a solution for me, since I want to keep the rows and just replace the error values.

In my case, my data table will change over the time, means the column name may change (e.g. years), or new columns appear. So the second possibility is too static, since I do not want to change the script each time.

So I’ve tried to get a dynamic way to clean all columns, indepent from the column names (and number of columns). It replaces the errors by a null value.

let
    Source = Excel.CurrentWorkbook(){[Name="Tabelle1"]}[Content],

    //Remove errors of all columns of the data source. ColumnName doesn't play any role
    Cols = Table.ColumnNames(Source),
    ColumnListWithParameter = Table.FromColumns({Cols, List.Repeat({""}, List.Count(Cols))}, {"ColName" as text, "ErrorHandling" as text}),
    ParameterList = Table.ToRows(ColumnListWithParameter ),
    ReplaceErrorSource = Table.ReplaceErrorValues(Source, ParameterList)
in
    ReplaceErrorSource

Here the different three queries messages, after I’ve added two new column (with errors) to the source:

If anybody has another solution to make this kind of data cleaning, please write your post here.

You’d often run into data sets with errors especially when the source is excel. If you have been working with Power Query you know that it doesn’t like error values and truncates the entire row which has an error in any column.

Sad. But you can obviously do Replace Errors and fix them with null values, however the challenge is that, the Replace Errors should automatically work on even the new columns added in data.

Video First ?

Consider this 3 column data

Replace Error Values in Multiple Columns Power Query - Data
Now obviously when this is loaded in Power Query it will show error wherever #N/A (and for any other type of excel errors)

Replace Error Values in Multiple Columns Power Query - Data Error

You can easily fix this

  • Select all columns
  • Transform Tab >> Replace Values Drop Down >> Replace Errors >> type null
  • Done

But what if the 4th column is added and has error values, the Replace Errors will not automatically extend to the 4th column. Let’s do that!

Replace Error Values in Multiple Columns

Step 1 –

  • I extract all the columns names as a list.
  • Click on fx and write the M code below
  • I do this as a second step after Source (data loading)
=Table.ColumnNames(Source)

Replace Error Values in Multiple Columns Power Query - Step 1

Step 2 – Since a Table offers more options to work as compared to a List. Covert the List to a Table. Right click on the List (header) >> To Table.

Step 3 – From the Add Columns Tab >> Custom Column >> type =null

  • This will add a Custom Column will null values across all rows.
  • I am doing this because I want to replace all error values with null.

The result looks like this

Replace Error Values in Multiple Columns Power Query - Null Column

Step 4 – Next I will transpose this table. Transform Tab >> Transpose.

Replace Error Values in Multiple Columns Power Query - Transposed Table

Understanding whats going on..

If you are still with me, so far you have blindly pursued the steps. Let me help you understand where are we headed.

Replace Error Values in Multiple Columns Power Query - Manual

  • When you do Replace Errors the highlighted (in yellow) code appears.
  • Notice that column names – One, Two and Three are hard coded. They wont change if the column names changes or source data adds a new column.
  • Also note that the column names are in double curly brackets {{ }}. Which means it’s a list inside a list.
  • We are trying to create the same list of list with 2 parts – Column Name and null value. But a dynamic one!
  • Let’s proceed

Step 5 – Convert the table into a list of list.

  • Use the fx button to write a short M Code
  • This will convert each column into a list and then make a single list of all lists
  • Renamed the step to ColList (it’s optional but nice to have good labels across)
= Table.ToColumns(#'Transposed Table')

Replace Error Values in Multiple Columns Power Query - Zipped list

Step 6 – It’s time now to feed the list in Replace Errors

  • Using the fx I’ll create a new Step
  • Write the following Code. In the code Source is the Step (which has the table with error values) and ColList is our List of List which replaces all errors dynamically with null.
= Table.ReplaceErrorValues(Source, ColList)

Replace Error Values in Multiple Columns Power Query - Replace Errors Dynamic

Bingo! 😎

Some more cool stuff on Power Query!

  1. Make Remove Other Columns Dynamic in Power Query
  2. Dynamic Column Renaming
  3. Running Total in Power Query
  4. Video – Combine Data from Multiple Excel File – With Dynamic Sheets and Columns

I have an awesome Course on Power Query, you must check it out..

Power Query Training

Course Details are here   |   Course Outline (pdf) is here

Chandeep

Welcome to Goodly! My name is Chandeep.
On this blog I actively share my learning on practical use of Excel and Power BI. There is a ton of stuff that I have written in the last few years. I am sure you’ll like browsing around.
Please drop me a comment, in case you are interested in my training / consulting services. Thanks for being around
Chandeep

Замените все значения ошибок для всех столбцов после импорта данных (при сохранении строк)

Обновлено

Вопрос:

Таблица Excel в качестве источника данных может содержать значения ошибок (#NA, # DIV/0), которые могут нарушить некоторые последующие этапы процесса преобразования в Power Query.
В зависимости от следующих шагов мы можем получить не вывод, а ошибку. Так как же справиться с этим делом?

Я нашел два стандартных шага в Power Query, чтобы поймать их:

  • Удалить ошибки (интерфейс: Главная/Удалить строки/Удалить ошибки) → все строки с ошибками будут удалены
  • Заменить значения ошибок (UI: Transform/Replace Errors) → столбцы должны быть сначала выбраны для выполнения этих операций.

Первая возможность для меня не является решением, так как я хочу сохранить строки и просто заменить значения ошибок.

В моем случае моя таблица данных будет меняться со временем, это означает, что имя столбца может измениться (например, годы) или появятся новые столбцы. Так что вторая возможность слишком статична, так как я не хочу каждый раз менять скрипт.

Поэтому я попытался получить динамический способ очистки всех столбцов, независимо от имен столбцов (и количества столбцов). Он заменяет ошибки на нулевое значение.

let
Source = Excel.CurrentWorkbook(){[Name="Tabelle1"]}[Content],

//Remove errors of all columns of the data source. ColumnName doesn't play any role
Cols = Table.ColumnNames(Source),
ColumnListWithParameter = Table.FromColumns({Cols, List.Repeat({""}, List.Count(Cols))}, {"ColName" as text, "ErrorHandling" as text}),
ParameterList = Table.ToRows(ColumnListWithParameter ),
ReplaceErrorSource = Table.ReplaceErrorValues(Source, ParameterList)
in
ReplaceErrorSource

Вот разные три сообщения с запросами, после того как я добавил два новых столбца (с ошибками) к источнику:

Если у кого-то есть другое решение для такой очистки данных, напишите здесь.

Лучший ответ:

let
    src = Excel.CurrentWorkbook(){[Name="Tabelle1"]}[Content],
    cols = Table.ColumnNames(src),
    replace = Table.ReplaceErrorValues(src, List.Transform(cols, each {_, "!"}))
in
    replace

I’m trying to execute a step in PowerQuery that replaces error values with one of two possible values.
The values in [B] would be 1 or 0 depending on the value of [A] (less than 5).

My statement returns a Function instead of a value, but I can’t see why:

= Table.ReplaceErrorValues(#"Step x", {{"B", each if [A] < 5 then 0 else 1}})

I’ve used the same conditional syntax for simple .Replace statements, but I’m wondering if I can’t put the condition in a curly braces list. Can anyone see what I’m doing wrong here?

asked Jun 2, 2021 at 3:03

Ambie's user avatar

1

Instead of using Table.ReplaceErrorValues you could instead use a try/otherwise wherever that «Error» value is being generated. For instance, if your previous step is…

#"Step x" = Table.AddColumn(#"Step y", "B", each [C] / [D]) // Error if [D] = 0!

… then you could change it to something like…

#"Step x" = Table.AddColumn(#"Step y", "B", each
    try [C] / [D]    // Error if [D] = 0!
    otherwise if [A] < 5 then 0 else 1)

This way, you never have the Error values in the first place!

answered Jun 2, 2021 at 8:57

JDCAce's user avatar

JDCAceJDCAce

15912 bronze badges

1

There doesn’t seem to be an obvious way of creating the conditional clause in the Table.ReplaceErrorValues() function. I suspect it has something to do with how the iteration works.

The only workaround I could think of was to make the Table.ReplaceErrorValues() replace errors with a spurious value, -1 in my case, and then call the ReplaceValue() function, which can accept the conditional clause:

= Table.ReplaceErrorValues(#"Step x", -1)
= Table.ReplaceValue(#"Replaced Errors",-1,each if [A] < 5 then 0 else 1,Replacer.ReplaceValue,{"B"})

answered Jun 24, 2021 at 22:38

Ambie's user avatar

AmbieAmbie

4,9072 gold badges12 silver badges26 bronze badges

Понравилась статья? Поделить с друзьями:
  • Как забыть об ошибках прошлого
  • Как избавиться от ошибки 0x80240017
  • Как забыть о своих ошибках
  • Как достать соседа на windows 10 выдает ошибку
  • Как избавиться от ошибки 0x000007b