Welcome, Guest
You have to register before you can post on our site.

Username
  

Password
  





Search Forums

(Advanced Search)

Forum Statistics
» Members: 20,946
» Latest member: blackopsdlc
» Forum threads: 22,010
» Forum posts: 22,977

Full Statistics

Online Users
There are currently 1416 online users.
» 0 Member(s) | 1410 Guest(s)
Applebot, Baidu, Bing, Facebook, Google, Yandex

Latest Threads
[DevBlog MS] Microsoft is...
Forum: C#, Visual Basic, & .Net Frameworks
Last Post: xSicKxBot

» Replies: 0
» Views: 11
[WoW Retail News] BlizzCo...
Forum: World of Warcraft
Last Post: xSicKxBot

» Replies: 0
» Views: 13
What is Celestial Codex i...
Forum: PC Discussion
Last Post: xSicKxBot

» Replies: 0
» Views: 13
[Ubuntu News] Fine tune y...
Forum: Linux, FreeBSD, and Unix types
Last Post: xSicKxBot

» Replies: 0
» Views: 11
[WoW Retail News] Xal'ata...
Forum: World of Warcraft
Last Post: xSicKxBot

» Replies: 0
» Views: 31
[Ubuntu News] Scaling And...
Forum: Linux, FreeBSD, and Unix types
Last Post: xSicKxBot

» Replies: 0
» Views: 22
[WoW Retail News] Comment...
Forum: World of Warcraft
Last Post: xSicKxBot

» Replies: 0
» Views: 20
How to unlock Maya Aguina...
Forum: PC Discussion
Last Post: xSicKxBot

» Replies: 0
» Views: 25
[Steam Release] The Unive...
Forum: New Game Releases
Last Post: xSicKxBot

» Replies: 0
» Views: 30
[DevBlog MS] Creating a m...
Forum: C#, Visual Basic, & .Net Frameworks
Last Post: xSicKxBot

» Replies: 0
» Views: 38

 
  [Tut] Check for NaN Values in Python
Posted by: xSicKxBot - 04-09-2022, 06:56 AM - Forum: Python - No Replies

Check for NaN Values in Python

Overview


Problem: How to check if a given value is NaN?

Here’s a quick look at the solutions to follow:

import math
import numpy as np
import pandas as pd x = float('nan')
print(math.isnan(x))
print(x != x)
print(np.isnan(x))
print(pd.isna(x))
print(not(float('-inf') < x < float('inf')))

So, what is a NaN value?

NaN is a constant value that indicates that the given value is Not a Number. It’s a floating-point value, hence cannot be converted to any other type other than float. We should know that NaN and Null are two different things in Python. The Null values indicate something which does not exist, i.e. is empty. But that is not the case with NaN.

We have to deal with NaN values frequently in Python especially when we deal with array objects or DataFrames. So, without further delay, let us dive into our mission critical question and have a look at the different methods to solve our problem.

Method 1: Using math.isnan()


The simplest solution to check for NaN values in Python is to use the mathematical function math.isnan().

math.isnan() is a function of the math module in Python that checks for NaN constants in float objects and returns True for every NaN value encountered and returns False otherwise.

Example:

# Importing the math module
import math # Function to check for NaN values
def isNaN(a): # Using math.isnan() if math.isnan(a): print("NaN value encountered!") else: print("Type of Given Value: ", type(a)) # NaN value
x = float('NaN')
isNaN(x)
# Floating value
y = float("5.78")
isNaN(y)

Output:

NaN value encountered!
Type of Given Value: <class 'float'>

In the above example, since x represents a NaN value, hence, the isNaN method returns True but in case of y , isNan returns False and prints the type of the variable y as an output.

Method 2: Hack NaN Using != Operator


The most unique thing about NaN values is that they are constantly shapeshifting. This means we cannot compare the NaN value even against itself. Hence, we can use the != (not equal to) operator to check for the NaN values. Thus, the idea is to check if the given variable is equal to itself. If we consider any object other than NaN, the expression (x == x) will always return True. If it’s not equal, then it is a NaN value.

Example 1:

print(5 == 5)
# True
print(['a', 'b'] == ['a', 'b'])
# True
print([] == [])
# True
print(float("nan") == float("nan"))
# False
print(float("nan") != float("nan"))
# True

Example 2:

# Function to check for NaN values
def not_a_number(x): # Using != operator if x != x: print("Not a Number!") else: print(f'Type of {x} is {type(x)}') # Floating value
x = float("7.8")
not_a_number(x)
# NaN value
y = float("NaN")
not_a_number(y)

Output:

Type of 7.8 is <class 'float'>
Not a Number!

Method 3: Using numpy.isnan()


We can also use the NumPy library to check whether the given value is NaN or not. We just need to ensure that we import the library at the start of the program and then use its np.isnan(x) method.

The np.isnan(number) function checks whether the element in a Numpy array is NaN or not. It then returns the result as a boolean array.

Example: In the following example we have a Numpy Array and then we will check the type of each value. We will also check if it is a NaN value or not.

import numpy as np arr = np.array([10, 20, np.nan, 40, np.nan])
for x in arr: if np.isnan(x): print("Not a Number!") else: print(x, ":", type(x))

Output:

10.0 : <class 'numpy.float64'>
20.0 : <class 'numpy.float64'>
Not a Number!
40.0 : <class 'numpy.float64'>
Not a Number!

?TRIVIA

Let us try to perform some basic functions on an numpy array that involves NaN values and find out what happens to it.

import numpy as np arr = np.array([10, 20, np.nan, 40, np.nan])
print(arr.sum())
print(arr.max())

Output:

nan
nan

Now this can be a problem in many cases. So, do we have a way to eliminate the NaN values from our array object and then perform the mathematical operations upon the array elements? Yes! Numpy facilitates us with methods like np.nansum() and np.nanmax() that help us to calculate the sum and maximum values in the array by ignoring the presence of NaN values in the array.

Example:

import numpy as np arr = np.array([10, 20, np.nan, 40, np.nan])
print(np.nansum(arr))
print(np.nanmax(arr))

Output:

70.0
40.0

Method 4: Using pandas.isna()


Another way to solve our problem is to use the isna() method of the Pandas module. pandas.isna() is a function that detects missing values in an array-like object. It returns True if any NaN value is encountered.

Example 1:

import pandas as pd x = float("nan")
y = 25.75
print(pd.isna(x))
print(pd.isna(y))

Output:

True
False

Example 2: In the following example we will have a look at a Pandas DataFrame and detect the presence of NaN values in the DataFrame.

import pandas as pd df = pd.DataFrame([['Mercury', 'Venus', 'Earth'], ['1', float('nan'), '2']])
print(pd.isna(df))

Output:

 0 1 2
0 False False False
1 False True False

Method 5: By Checking The Range


We can check for the NaN values by using another NaN special property: limited range. The range of all the floating-point values falls within negative infinity to infinity. However, NaN values do not fall within this range.

Hence, the idea is to check whether a given value lies within the range of -inf and inf. If yes , then it is not a NaN value else it is a NaN value.

Example:

li = [25.87, float('nan')]
for i in li: if float('-inf') < float(i) < float('inf'): print(i) else: print("Not a Number!")

Output:

25.87
Not a Number!

Recommended read: Python Infinity

Conclusion


In this article, we learned how we can use the various methods and modules (pandas, NumPy, and math) in Python to check for the NaN values. I hope this article was able to answer your queries. Please stay tuned and subscribe for more such articles. 

Authors: SHUBHAM SAYON and RASHI AGARWAL


Do you want to become a NumPy master? Check out our interactive puzzle book Coffee Break NumPy and boost your data science skills! (Amazon link opens in new tab.)

Coffee Break NumPy



https://www.sickgaming.net/blog/2022/03/...in-python/

Print this item

  [Oracle Blog] Announcing 2018 Duke's Choice Award Winners
Posted by: xSicKxBot - 04-09-2022, 06:56 AM - Forum: Java Language, JVM, and the JRE - No Replies

Announcing 2018 Duke's Choice Award Winners

In keeping with its 16-year history, the 2018 Duke's Choice Award winners were announced at the Groundbreakers Hub at Code One. The winners include JPoint, a self-driving car; community winners BgJUG (the Bulgarian JUG) . Among the winners announced were also tools from ClassGraph, Twitter4J, Apache...

https://blogs.oracle.com/java/post/annou...rd-winners

Print this item

  (Indie Deal) Fantastic Tales Bundle, MHR Sunbreak & Racing Deals
Posted by: xSicKxBot - 04-09-2022, 06:56 AM - Forum: Deals or Specials - No Replies

Fantastic Tales Bundle, MHR Sunbreak & Racing Deals

Visual Choice Bundle | 7 VN Steam Games | 93% OFF
[www.indiegala.com]
Be it linear or multiple endings, in these story rich Visual Novels your choice matters! Featuring various art styles and themes like romance, adventure, horror, drama etc.

Choose with what interactive fiction to start: Fires At Midnight, Tell a Demon, Pumpkin Eater, Code Romantic, Gear of Glass: Eolarn's war, Mysteria of the World: The forest of Death & The Evolving World: Catalyst Wake.

https://www.youtube.com/watch?v=15fDyFE48eQ
505 Games Racing Sale, up to 80% OFF
[www.indiegala.com]
Stay Inside, Stay Safe and Enjoy Good Games.
Check out IndieGala on Twitter, YouTube & Facebook[www.facebook.com]


https://steamcommunity.com/groups/indieg...0014718450

Print this item

  PC - Persona 4 Arena Ultimax
Posted by: xSicKxBot - 04-09-2022, 06:56 AM - Forum: New Game Releases - No Replies

Persona 4 Arena Ultimax



In P4AU, the characters from Persona 4 and Persona 3 once again find themselves teaming up to face off in the P-1 Climax, a series of battles which must be won before the world ends. The original cast of characters from Persona 3 and 4 are back to discover the mastermind behind the whole tournament, while a few new faces join the fight, including Junpei Iori, Yukari Takeba, Rise Kujikawa, and more. But standing in their way is the dual katana-wielding Sho Minazuki, a huge threat to everyone involved in the P-1 Climax. Worse yet, there's a Sho lookalike who can wield a Persona...

Publisher: Sega

Release Date: Mar 17, 2022




https://www.metacritic.com/game/pc/perso...na-ultimax

Print this item

  News - Halo Infinite Season 2: Lone Wolves Trailer Shows Off What's Coming Next
Posted by: xSicKxBot - 04-09-2022, 06:56 AM - Forum: Lounge - No Replies

Halo Infinite Season 2: Lone Wolves Trailer Shows Off What's Coming Next

Halo Infinite's Season 2: Lone Wolves is coming soon, and 343 Industries has released a new trailer for it that offers a glimpse of what to expect when it arrives May 3.

This includes new maps for Arena and BTB, as well as more modes like the battle royale-style Last Spartan Standing. Players are also getting a new battle pass, and like all Halo Infinite battle passes, it will never expire, so players don't need to rush to complete it before the end of a given season.

According to Halo community director Brian Jarrard, nearly everything on display in the Season 2 is included with the new battle pass either by spending money or grinding. In addition, there will be new items added to the shop and more free event passes throughout Season 2.

Continue Reading at GameSpot

https://www.gamespot.com/articles/halo-i...01-10abi2f

Print this item

  [Oracle Blog] How to Develop Modules with Eclipse IDE
Posted by: xSicKxBot - 04-08-2022, 10:16 AM - Forum: Java Language, JVM, and the JRE - No Replies

How to Develop Modules with Eclipse IDE

The Java Platform Module System (JPMS) main goal is to make it easier to construct and maintain Java libraries and large applications. You will also experience improved application performance by scaling down the Java SE platform and JDK. In a series of five tutorials, Deepak Vohra explains how to u...

https://blogs.oracle.com/java/post/how-t...clipse-ide

Print this item

  [Tut] Is There A Way To Create Multiline Comments In Python?
Posted by: xSicKxBot - 04-08-2022, 10:16 AM - Forum: Python - No Replies

Is There A Way To Create Multiline Comments In Python?

Summary: You can use consecutive single-line comments (using # character) to create a block of comments (multiline comments) in Python. Another way is to use """ quotes to enclose the comment block.


Problem Statement: How to create multiline comments in Python?

Other programming languages like C++, Java, and JavaScript, have an inbuilt mechanism (block comment symbols) for multiline comments, but there is no built-in mechanism for multiline comments in Python. Hence, the following code won’t work:

/* This is a multiline Comment in Python */

The above code will throw an error in Python. However, there are still some workarounds to using the multiline comments in Python. Let’s look at the different methods to do this in this article.

  • Quick Trivia on Comments:
    • Comments are a very important part of every programming language as it explains the logic used in the code. The developers provide these comments to make it more readable and for the users to get a better understanding of the code. The comments don’t run as they are ignored by the interpreters and compilers. Comments also help us while we are debugging, i.e., when there are two lines of code, we can comment one out to prevent it from running.
  • What is a multiline comment in Python?
    • A multiline comment in Python is a comment that generally expands to multiple lines, i.e., multiline comments are the comments that expand to two or more lines in the source code.

Method 1: Using Multiple Single Line Comments


We can use the multiple single-line comments to create multiline comments in Python. But first, you must know how to make a single-line comment is in Python. The Hash character (#) is used to make single-line comments in Python. The commented line does not get printed in the output.

Example:

# print("Hello Finxters")
print("Learning to create multiline comments in Python")

Output:

Learning to create multiline comments in Python

Now let’s create multiline comments using consecutive single line comments:

Example:

print("Learning to create multiline comments in Python")
# print("Hello Finxters")
# print("This is a")
# print("Multiline comment")
# print("in Python")
print("End of program")

Output:

Learning to create multiline comments in Python End of program

As we can see that the commented lines are ignored by the parser in Python, thereby creating a block of comments.

Discussion: Using single-line comments to comment out every line of a multiline comment individually becomes a very tedious process. Hence this method is not recommended to be used when you are not using any modern editor. However, most of the new code editors have a shortcut for block commenting in Python. You can just select a few lines of code using shift and the cursor keys and then press cmd + / (This shortcut may differ depending upon the editor you are using) to comment them out all at once. You can even uncomment them easily by simply selecting the block of comments and pressing the cmd + / keyboard shortcut.

Method 2: Using Docstrings Or Multiline Strings


We can create the multiline comments using multiline strings or docstrings in Python. This method has the same effect but is generally used for documentation strings, not block comments. However, if you want to comment things out temporarily, you can use this method. Python has two types of docstrings-
1) One-Line docstrings
2) Multiline docstrings.

To create a block comment, we use the multiline docstrings. Let’s create multiline comments using docstrings in the following example:

Example 1:

print("Learning to create multiline comments in Python") '''
print("Hello Finxters")
print("This is a")
print("Multiline comment")
print("in Python") '''
print("End of program")

Output:

Learning to create multiline comments in Python End of program

Example 2: Suppose you want to define a block comment inside a function using docstrings you have to do it the following way:

def multiply(x, y): res = x * y """ This is a multiline comment indented properly This function returns the result after multiplying the two numbers """ return res
print("The multiplication of the two numbers is", multiply(10, 5))

Output:

The multiplication of the two numbers is 50
  • Caution:
    • You must always ensure that you have used the indentation for the first """ correctly; otherwise, you may get a SyntaxError.
    • Also, if you are opening a multiline comment using three double quotes """ then you must ensure that you enclose the block with exactly three double quotes as well. If you do nt follow this convention, you will get an error again. For example – if you open a multiline comment with three double quotes and close it using three single quotes, then you will get an error.

Example I: If you don’t intend """ properly, you may get the following error:

def multiply(x, y): res = x * y """ This is a multiline comment indented properly This function returns the result after multiplying the two numbers """ return res
print("The multiplication of the two numbers is", multiply(10, 5))

Output:

File "main.py", line 10 return res ^ IndentationError: unexpected indent

Example II: Let’s visualize what happens when there is a mismatch between the type of triple quotes used.

def multiply(x, y): res = x * y """ This is a multiline comment indented properly This function returns the result after multiplying the two numbers ''' return res
print("The multiplication of the two numbers is", multiply(10, 5))

Output:

 File "C:\Users\SHUBHAM SAYON\PycharmProjects\Finxter\General\rough.py", line 10 print("The multiplication of the two numbers is", multiply(10, 5)) ^ SyntaxError: EOF while scanning triple-quoted string literal

Note: You must always be careful where you place these multiline comments in the code. If it is commented right after a class definition, function, or at the start of a module, it turns into a docstring that has a different meaning in Python.

Example:

def multiply(x, y): """ This is a multiline comment made right after the function definition It now becomes a function docstring associated with the function object that is also accessible as runtime metadata """ res = x * y return res
print("The multiplication of the two numbers is", multiply(10, 3))

Output:

The multiplication of the two numbers is 30

?The difference between the comment and the parser is that the comment is removed by the parser, whereas a docstring can be accessed programmatically at runtime and ends up in the byte code. 

Conclusion


Therefore, in this tutorial, we learned two ways of creating multiline comments in Python –
➨Using consecutive single-line comments.
➨Multiline strings (docstrings).

That’s all for this article. I hope you found it helpful. Please stay tuned and subscribe for more interesting articles and tutorials in the future. Happy learning!

?Authors: Rashi Agarwal and Shubham Sayon


Recommended Read:



https://www.sickgaming.net/blog/2022/03/...in-python/

Print this item

  (Indie Deal) FREE Cursed Sight, Star Wars & Lego Sale
Posted by: xSicKxBot - 04-08-2022, 10:16 AM - Forum: Deals or Specials - No Replies

FREE Cursed Sight, Star Wars & Lego Sale

Cursed Sight FREEbie
[freebies.indiegala.com]
Culminating our Anime Sale[www.indiegala.com] with one final themed FREEbie, Cursed Sight, a truly touching & emotional story featuring branching narratives.

https://www.youtube.com/watch?v=4LE4bocTH0Q
Star Wars & Lego Sale, EMEA ONLY, ALL TITLES 75% OFF
[www.indiegala.com]
Stay Inside, Stay Safe and Enjoy Good Games.
Check out IndieGala on Twitter, YouTube & Facebook[www.facebook.com]


https://steamcommunity.com/groups/indieg...4094824772

Print this item

  (Free Game Key) Rogue Legacy & The Vanishing of Ethan Carter - Free Epic Games
Posted by: xSicKxBot - 04-08-2022, 10:16 AM - Forum: Deals or Specials - No Replies

Rogue Legacy & The Vanishing of Ethan Carter - Free Epic Games

Visit the store page and add the games to your account:

Rogue Legacy[store.epicgames.com]

The Vanishing of Ethan Carter[store.epicgames.com]

The Vanishing of Ethan Carter is a recurring giveaway, being given once on the Epic Store on Dec 2021. The games are free to keep until Apr 14th 2022 - 15:00 UTC.

Next week's freebie:
Insurmountable
XCOM 2

We are welcoming everyone to join our discord[discord.gg]. We are more active there on finding giveaways, small or large, and there are daily raffles you can participate.

?GrabFreeGames.com ?Twitter ?Steam Curator ?Facebook[fb.me]?Discord[discord.gg]
❤️Support us: ✔️HumbleBundle Partner[www.humblebundle.com] Epic Tag: GrabFreeGames


https://steamcommunity.com/groups/GrabFr...8424187425

Print this item

  PC - Monster Energy Supercross - The Official Videogame 5
Posted by: xSicKxBot - 04-08-2022, 10:16 AM - Forum: New Game Releases - No Replies

Monster Energy Supercross - The Official Videogame 5



Enjoy all new customization possibilities with our enhanced Track Editor, and give a boost to your creativity! Mix and match pre-existing modules with the brand new Rhythm Section Editor, to design complex prefab track sections, ready to be shared with the Community. Creating amazing jumps has never been easier. Bring the challenge to a whole new level of fun with the new Split Screen Mode, for exciting Multiplayer challenges to race shoulder to shoulder with your friends on the couch! And when the couch is not enough, compete in exciting races online against the whole world.

Publisher: Milestone S.r.l

Release Date: Mar 17, 2022




https://www.metacritic.com/game/pc/monst...ideogame-5

Print this item