Ошибка nan в power query

SharePoint Online training courses

In this Microsoft Power BI Tutorial, We will discuss how we can fix error “Power BI NaN (Not a number) while dividing by Zero“.

In Power BI Desktop, I have a table named as Income Tax Rates which has below columns as:

  • Country (Choice Data type)
  • Net Wage Earnings After Tax (Currency Data type)
  • Income Tax Rate (Number Data type)
  • Employee Social Security Contributions (Number Data type)
  • Net Wage Bonus (Currency Data type)

As per my requirement, I wanted to calculate the total Income Tax Variance (Income Tax Rate/Employee Social Security Contributions) of Iceland whose rank is 3 like the below screenshot.

NaN error in Power BI

In the Power BI Desktop, Get the SharePoint List from SharePoint Online Site to your Power BI Desktop. Follow the below link to get the SharePoint List to Power BI Desktop:

Load SharePoint List to Power BI Desktop

Now format the columns which are having different Data types in Power BI Desktop. In the below screenshot, I have changed the below column Data types as:

  • Employee Social Security Contributions (Whole Number)
  • Income Tax Rate (Whole Number)
  • Net Wage Bonus (Whole Number)
  • Net Wage Earnings After Tax (Whole Number)
power bi NaN error

Now I have retrieved the Column (Employee Social Security Contribution) value of Country (Iceland) by using the below Power BI measure formula:

if nan power query

Similarly, I have retrieved the Column (Income Tax Rate) value of Country (Iceland) by using the below Power BI measure formula:

nan error power bi

And then I have divided these above columns to get the total variance of Country (Iceland). For that, I have used this below Power BI measure formula.

what is nan in power bi

While I have added the Measure [Total Income Variance (Iceland)] in a Card visual, then the result was appearing as NaN which you can see in the below screenshot.

nan in power bi

Power BI NaN (Not a number) while dividing by Zero

Basically, In the Power BI Desktop, We are getting the error NaN when we are dividing the value as 0 by 0.

To resolve this NaN issue, We have to follow these below steps:

Step-1:

First of all, Go to the Home tab and then click on Edit Queries from the ribbon. Select Edit Queries from the drop-down as shown below.

power bi replace nan with blank

Step-2:

Once you will click on the Edit Queries option, then the below query editor window will appear. In this window, Go to the Add Column tab and then Click on Custom Column.

replace nan with 0 power query

Step-3:

Now a Custom Column window will appear where you have to write the Custom Column Query formula for the error NaN.

Enter a new column name and put the below Query formula in Custom column formula field:

Income Variance= if Number.IsNaN(0/0) then 0 else 1
  • Here, New column name = Income Variance
  • Custom column formula = if Number.IsNaN(0/0) then 0 else 1

By using a double click, you can insert the Available columns if you want otherwise click on OK Button as like below screenshot.

what does nan in power bi mean

Step-4:

Now you can see the new custom column(Income Variance) will be created in the Query Editor window.

After that, do not forget to click on the Close & Apply button. Go to the Home tab and click on Close & Apply option as like the below figure.

what does nan mean in power bi

Step-5:

Now to test the new custom column, Take a Card under the Visualizations section and insert the custom column (Income Variance) into the Fields section of the card. Then in the Card, you can see the value will be appearing as 0.

As per my requirement, I wanted the Income Variance field as Percentage variance, that’s why I have formatted the data type as Percentage.

handle nan in power bi

Also, You may like following Power BI tutorials:

  • Power BI report using People Picker Field
  • Microsoft Power BI Error: This content isn’t available
  • Access to the resource is forbidden error in Power BI
  • [Video Tutorial] Create Power BI Dashboard step by step tutorial
  • DAX Filter function (Text column) in Power BI
  • Power BI Measure Sum and Subtract Example
  • Get Current Month Sales Report using Power BI Measure
  • Get Next Month Sales Report in Power BI
  • Data Labels in Power BI
  • Subtraction in Power bi using DAX
  • Power BI Group By Examples
  • Power bi shared dataset permissions management
  • Scheduled Power BI report data refresh
  • How to change data source in Power Bi

Hence in this Microsoft Power BI Tutorial, We discussed how to fix error “Power BI NaN (Not a number) while dividing by Zero“.

Bhawana Rathore

Hello Everyone!! I am Bhawana a SharePoint MVP and having about 10+ years of SharePoint experience as well as in .Net technologies. I have worked in all the versions of SharePoint from wss to Office 365. I have good exposure in Customization and Migration using Nintex, Metalogix tools. Now exploring more in SharePoint 2016 🙂 Hope here I can contribute and share my knowledge to the fullest. As I believe “There is no wealth like knowledge and no poverty like ignorance”

Hi,

Is there an easy way to manage NaN or Infinity ?

I tried to replace error, no impact.

I tried to replace «NaN» by 0, no impact (when it’s working with Null).

In my formula I tried with «try a/b otherwise 0» but I still have the error.

I saw some test based on Number.IsNaN but it just tests NaN… what about Infinity or other errors…

The only way I found is to test Numerator and denominator (if Numerator=0 or Denominator = 0 then 0 else …. ), but maybe there is a better methodology like an equivalent to IFERROR in Excel? 

Thank you for your help.

(I’m using PowerQuery in Excel, so I don’t have DAX measures & operators).

 

Александр L

Hello Everyone!! I am Bhawana a SharePoint MVP and having about 10+ years of SharePoint experience as well as in .Net technologies. I have worked in all the versions of SharePoint from wss to Office 365. I have good exposure in Customization and Migration using Nintex, Metalogix tools. Now exploring more in SharePoint 2016 🙂 Hope here I can contribute and share my knowledge to the fullest. As I believe “There is no wealth like knowledge and no poverty like ignorance”

Hi,

Is there an easy way to manage NaN or Infinity ?

I tried to replace error, no impact.

I tried to replace «NaN» by 0, no impact (when it’s working with Null).

In my formula I tried with «try a/b otherwise 0» but I still have the error.

I saw some test based on Number.IsNaN but it just tests NaN… what about Infinity or other errors…

The only way I found is to test Numerator and denominator (if Numerator=0 or Denominator = 0 then 0 else …. ), but maybe there is a better methodology like an equivalent to IFERROR in Excel? 

Thank you for your help.

(I’m using PowerQuery in Excel, so I don’t have DAX measures & operators).

 

Александр L

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

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

Александр

Коллеги Всем привет , подскажите пжл возможно ли с помощь Try  в Power Query при добавлении доп столбца формулой прописать аналог EСЛИОШИБКА ?
Мне просто необходимо чтобы при расчёте выводился ноль если происходит ошибка.
Спасибо  

 

PooHkrd

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

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

Excel x64 О365 / 2016 / Online / Power BI

#2

14.02.2019 13:37:57

try чего-то там otherwise что-то вместо ошибки
так.
В вашем случае нужно понимать что PQ деление на ноль не воспринимает как именно ошибку, для него это вполне существующее значение. Посему настоятельно керемендую перед делением осуществлять проверку знаменателя на равенство нулю:

Код
=if [#"Количество (в базовых единицах), короба"] * [Вложения] = 0 then 0 else [База]/([#"Количество (в базовых единицах), короба"] * [Вложения])

Изменено: PooHkrd14.02.2019 13:44:59

Вот горшок пустой, он предмет простой…

 

Александр L

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

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

Александр

#3

14.02.2019 13:39:34

Код
=try ([База]/([#"Количество (в базовых единицах), короба"]*[Вложения])) otherwise 0

Так у меня вроде так и прописано когда создаю  доп столбец но не работает

Изменено: Александр L14.02.2019 13:40:20
(вставил формулу)

 

Максим Зеленский

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

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

Microsoft MVP 2018-2022

#4

14.02.2019 13:42:15

Проще всего так:

Код
=if ([#"Количество (в базовых единицах), короба"]*[Вложения]) = 0 then 0 else ([База]/([#"Количество (в базовых единицах), короба"]*[Вложения]))

Еще можно — создать столбец =[#»Количество (в базовых единицах), короба»]*[Вложения] и использовать в формуле его, чтобы не считать два раза, а потом удалить.

F1 творит чудеса

 

Максим Зеленский

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

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

Microsoft MVP 2018-2022

#5

14.02.2019 13:44:00

Цитата
Александр L написал:
у меня вроде так и прописано когда создаю  доп столбец но не работает

Потому что деление на 0 это не совсем ошибка, которая стопорит запрос:
0/0 = NaN,
20/0 = Infinity
-20/0 = -Infinity

F1 творит чудеса

 

Александр L

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

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

Александр

А вы вот как обошли я тоже пробовал через If но применял три условия и вот не получалось(((. Спасибо сейчас попробую на массиве этот метод.

 

А ещё есть null, деление на который даёт null, а не ошибку и не упомянутое выше

 

Александр L

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

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

Александр

#8

14.02.2019 13:48:21

да с null  я всегда пресекаю на начальном этапе)))))

Avatar

P B

Member

Members

Level 0

Forum Posts: 38

Member Since:
March 8, 2021

sp_UserOfflineSmall
Offline

1

April 22, 2021 — 9:01 am

sp_Permalink
sp_Print

Hello Mynda,

What is the best approach to handle NaN Errors in Power Query? I have a table which is using a couple of columns but I am concerned about  2 Columns for this calculation and that is A and B and the calculation is to be in %. The Formula my company is using is like this 

=A2/(A2+B2) This calculation will go into the 3rd column.

And now there are some records where values are zero. 

So two issues over here. When I Close and Load to the Table it will show me 4 errors and if I click on 4 Errors and it takes me back to PQ and over there it shows me those records where all values are zero in these 2 columns and 3rd column will show an error, NaN.

I used a Custom Column and used this Formula  =A2/(A2+B2) (Replacing it with actual column names).

Is there a better way to do this?

How do I change Values for NaN Errors?

I can’t replace Values of NaN with anything else. I wanted to put value like Undetermined or Undefined (That is what it is when you divide with 0)

Please advise

Thanks,

PB

NaN-Error-2021-04-21_18-30-45.pngImage Enlarger

Avatar

Mynda Treacy

Admin

Level 10

Forum Posts: 4526

Member Since:
July 16, 2010

sp_UserOfflineSmall
Offline

2

April 22, 2021 — 4:10 pm

sp_Permalink
sp_Print

Hi PB,

There is a function for NaN values which you can use in a custom column:

= if Number.IsNaN([A]/([A]+[B])) then null else [A]/([A]+[B])

Mynda

Avatar

P B

Member

Members

Level 0

Forum Posts: 38

Member Since:
March 8, 2021

sp_UserOfflineSmall
Offline

3

April 22, 2021 — 9:42 pm

sp_Permalink
sp_Print

Hello Mynda,

Thank you! I will try it right now.

Thanks,

PB

Hi team,

Today I really got a big headache of » Invalid cell value » error.

I got a table with 44 small tables and each small table look like this:

Each of these small tables get same structure and all the data types are correct and without any errors

However, when I try to expand these small tables and make them into a big table, I got the error message:

[DataFormat.Error] Invalid cell value ‘#N/A’.

I tried to use remove error function or replace error function while those ways are dead end and refuse to work.

Where does the error come from and how can I fix it?

The following query is the code before expand table and it works without anything wrong:

let
    Source = Folder.Files(«C:Userst.sun1DesktopBstarsellout»),
    #»Added Custom» = Table.AddColumn(Source, «Custom», each Excel.Workbook([Content])),
    #»Removed Other Columns» = Table.SelectColumns(#»Added Custom»,{«Custom»}),
    #»Expanded Custom» = Table.ExpandTableColumn(#»Removed Other Columns», «Custom», {«Name», «Data», «Item», «Kind», «Hidden»}, {«Name», «Data»,
«Item», «Kind», «Hidden»}),
    #»Uppercased Text» = Table.TransformColumns(#»Expanded Custom»,{{«Kind», Text.Upper}, {«Item», Text.Upper}}),
    #»Filtered Rows» = Table.SelectRows(#»Uppercased Text», each [Kind] = «SHEET»),
    #»Filtered Rows1″ = Table.SelectRows(#»Filtered Rows», each [Item] = «SAMSUNG»),
    #»Removed Other Columns1″ = Table.SelectColumns(#»Filtered Rows1″,{«Data»}),
    tb=(x)=>
    let
    ntb=Table.TransformColumnTypes(x,List.Transform(Table.ColumnNames(x),each {_,type text})),
    dt=List.Select
    (
    List.Transform
    (
    Record.ToTable(ntb{0})[Value],
    each try Date.From(_) otherwise null
    ),
    each _ <> null
    ),
    ud=List.Max(dt),
    cn={«Product Group»,»OEM Device», «Customer»} & List.Transform(dt, each Text.From(_)),
    ntb1=Table.PromoteHeaders(ntb),
    ntb2=Table.SelectRows(Table.SelectColumns(ntb1,cn), each [OEM Device]<>null),
    ntb3=Table.TransformColumns(ntb2,{{«Product Group», Text.Upper}, {«OEM Device», Text.Upper}, {«Customer», Text.Upper}}),
    dt1=
    List.Transform
    (
    List.Transform(dt,each Text.From(_)),
    each {_,Int64.Type}
    ),
    ntb4=Table.TransformColumnTypes(ntb3,dt1),
    ntb5=Table.UnpivotOtherColumns(ntb4, {«Product Group», «OEM Device», «Customer»}, «Date», «Sales»),
    ntb6=Table.TransformColumnTypes(ntb5,{{«Date», type date}, {«Sales», Int64.Type}}),
    ntb7=Table.AddColumn(ntb6,»Update Date»,each ud),
    ntb8=Table.TransformColumnTypes(ntb7,{«Update Date»,type date})

    in
    ntb8,
    nc=Table.AddColumn(#»Removed Other Columns1″,»NTB»,each tb([Data])),

»This line above is the procedure to setup 44 small table listed in above picture

    #»Removed Other Columns2″ = Table.SelectColumns(nc,{«NTB»}),
    #»Expanded NTB» = Table.ExpandTableColumn(#»Removed Other Columns2″, «NTB», {«Product Group», «OEM Device», «Customer», «Date», «Sales», «Update Date»},
{«NTB.Product Group», «NTB.OEM Device», «NTB.Customer», «NTB.Date», «NTB.Sales», «NTB.Update Date»})

» This line is the expand line and after this line get the error message when I choose a column and click «load more» button

in
    #»Expanded NTB»

Cheers,

Tom Sun

Понравилась статья? Поделить с друзьями:
  • Ошибка namespace std что это
  • Ошибка named argument not found
  • Ошибка name cannot begin with the character hexadecimal value
  • Ошибка name ap не соответствует формату
  • Ошибка n20 на стиральной машине indesit