Remove nan From List In Python?

Remove nan from list in Python

In python, nan is a special value used to represent missing values. In this article, we will discuss the properties of nan values. We will also look at different ways how we can remove nan values from list in python.

What is nan in python?

The nan values are special floating-point numbers defined in the math module and the numpy module in python. They are normally used to represent missing values in a given data.  

You can import and use nan values from the math module as follows.

Output:

Alternatively, you can import nan values from the numpy module as follows.

Output:

The nan values have a special property that two nan values are not equal to one another. If you will compare nan values for equality, the result will always be False. You can observe this in the following example.

Output:

On the contrary, two nan values are always considered unequal to one another. You can observe this in the following example.

Output:

How to remove nan from list in python?

As seen above, we cannot compare nan values to remove them from list. So, we will have to find some alternative ways. 

To check for nan values, we can convert all the elements in the list to string and then compare the string “nan” with the string values of the elements in the list. After that, we can remove the nan values from the list.

Alternatively, there are various in-built methods defined in the math module, numpy module, and the pandas module to check for nan values. We will discuss all these approaches to check for nan value and remove them from list in the next sections. 

Remove nan from list using the str() function

The most naive way to remove nan values from list is by using the str() function. The str() function is used to convert an object with any data type to a string. The str() function takes an object as an input argument and returns its string representation.

To remove nan values from list, we will first convert the value nan to a string and create an empty list newList to store the output. After that, we will traverse each element in the input list using a for loop, convert them to a string, and check if it is equal to the string “nan”. If the string representation of the element is not equal to “nan”, we will append the element to the newList using the append() method. The element whose string representation equals “nan” will be a nan value and will not be added to the newList

You can observe the entire process in the following example.

Output:

Instead of a for loop, we can also use list comprehension with the str()  function to remove the nan values from list in python as follows.

Output:

Remove nan from list using math.isnan() function

The math module in python provides us with the isnan() function with which we can check if a value is a nan value or not. The isnan() function takes a floating-point number or a number that can be converted into a floating-point number as an input argument and returns True if the input is nan. Otherwise, it returns False. You can observe this in the following example.

Output:

However, if the input argument cannot be changed into a floating-point number, the function will raise the TypeError exception as shown below.

Output:

You should understand that we cannot use math.isnan() function to check for nan values in a list if it has string values in it because it will cause an error.

To remove nan values from list in python using the math.isnan() function, we will first create an empty list named newList. After that, we will traverse each element of the list using a for loop and check if it is a nan value or not using the math.isnan() function. If the element is not a nan value, we will append it to the newList using the append() method. Otherwise, we will reject the element. After traversing the entire input list, we will get all the values that are not nan values in the newList.

You can observe this in the following example.

Output:

Instead of a for loop, we can also use list comprehension with the math.isnan() function to remove nan values from list in python as follows.

Output:

Remove nan from list using numPy.isnan() function

Instead of the isnan() function defined in the math module, we can also use the isnan() function defined in the numpy module to check if an object has a value nan or not. The numpy.isnan() function works in the same way as the math.isnan() function.

Output:

If the input argument cannot be converted to a floating-point value, the function will raise a TypeError exception as shown below.

Output:

You can use the numpy.isnan() function with a for loop to remove nan values from list. The approach used is similar to what we used while discussing the approach to remove nan values from list using math.isnan() function as you can see in the following example.

Output:

Instead of using a for loop, you can use the list comprehension and numpy.isnan() function to remove a nan value from list in python as follows.

Output:

Remove nan from list using pandas.isnull() function

Similar to math.isnan() and numpy.isnan(), the pandas module in python also provides us with the isnull() function to check for nan values. The pandas.isnull() function takes an object as an input argument and returns True if the object has nan value. Otherwise, it returns False.

Output:

You can observe that the isnull() function can also take strings as input arguments. So, we can use the pandas.isnull() function to remove nan values from list that may contain string values.

We will use the pandas.isnull() function to remove nan values from list using the for loop. The approach is similar to what we discussed to remove nan values from list using the math.isnan() function as you can see in the following example.

Output:

Instead of using a for loop, you can use the list comprehension and pandas.isnull() function to remove a nan value from list in python as follows.

Output:

Conclusion

In this article, we have discussed what is a nan value in python. We also discussed why we cannot check for a nan value using the equality operator. Finally, we discussed four ways to remove nan values from list in python. I would suggest you use math.isnan() function for checking for a nan value while removing nan values from list. This is because both numpy.isnan() and pandas.isnull() have higher execution cost compared to math.isnan(). However, if there might be string values present in the list, then you should use the approach using the str() function or the pandas.isnull() function.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

Was this post helpful?

Related Posts

  • 26 December

    Repeat List N Times in Python

    Table of ContentsUsing the * operatorUsing the numpy.repeat() functionUsing the list comprehension techniqueUsing the itertools.repeat() functionConclusion This tutorial will demonstrate how to repeat list n times in Python. Using the * operator To repeat list n times in Python, use the * operator. Star operator(*) is used to multiply list by number e.g. lst*3 and […]

  • 16 December

    Convert List to Comma Separated String in Python

    Table of ContentsUse .join() MethodUse .join() with map() MethodUse .join() with List Comprehension Use .join() Method To convert a list to a comma separated string in Python, use the .join() method. join() method takes all elements in an iterable and joins them into one string with delimiter as separator. [crayon-63dace8f116b1422787456/] [crayon-63dace8f116b8539177039/] First, we created a […]

  • 27 November

    Remove Punctuation from List in Python

    Table of ContentsUse for loop with replace() MethodUse Nested List ComprehensionUse str.translate() Function Use for loop with replace() Method To remove punctuation from list in Python: Use the for loop to iterate over each word (element) of given list. Use a nested loop to iterate over each character in the word. Use the if statement […]

  • 04 October

    Get Every Other Element in List in Python

    Table of ContentsGet Every Other Element in List in PythonUsing List SlicingUsing the list.append() function along with the range() functionUsing list comprehension and the range() function with conditionalsUsing list comprehension and the range() function with stepUsing the enumerate() function along with list comprehensionUsing a lambda functionConclusion. A list is one of the more versatile data […]

  • 23 September

    Add Tuple to List in Python

    Table of ContentsAdd tuple to list in PythonWays to Add Tuple to List in Python (adding the Tuple as An Element)Using the insert() Function to Add Tuple to List in PythonUsing the append() Function to Add Tuple to List in PythonWays to Add Tuple to List in Python (adding the Tuple’s Elements to A List)Using […]

  • 24 May

    Replace Comma with Space in List in Python

    Table of ContentsHow to replace comma with space in list in PythonUsing the replace() function to replace comma with space in list in PythonUsing the re.sub() function to replace comma with space in list in PythonUsing the split() and join() functions to replace comma with space in list in Python.Conclusion In this post, we will […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.