Python удалить nan из листа

How to Remove NaN from List in Python

To remove NaN from a list using Python, the easiest way is to use the isnan() function from the Python math module and list comprehension.

from math import nan, isnan list_with_nan= [0, 1, 3, nan, nan, 4, 9, nan] list_without_nan = [x for x in list_with_nan if isnan(x) == False] print(list_without_nan) #Output: [0, 1, 3, 4, 9]

You can also use the Python filter() function.

from math import nan, isnan list_with_nan= [0, 1, 3, nan, nan, 4, 9, nan] list_without_nan = list(filter(lambda x: isnan(x) == False, list_with_nan)) print(list_without_nan) #Output: [0, 1, 3, 4, 9]

The Python numpy module also provides an isnan() function that we can use to check if a value is NaN.

import numpy as np from numpy import nan list_with_nan = [0, 1, 3, nan, nan, 4, 9, nan] list_without_nan = [x for x in list_with_nan if np.isnan(x) == False] print(list_without_nan) #Output: [0, 1, 3, 4, 9]

When working with lists, it can be valuable to be able to easily filter and remove unwanted values from your list.

Читайте также:  Stack using array in php

One such situation where you may want to remove values from a list is if you have a lot of NaN in your list.

We can easily remove all NaN from a list using Python with list comprehension. List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.

We can use list comprehension to remove all instances of a value in a list easily.

To check if an item in a list is NaN, we can use the isnan() function from the math module.

Below is the code which will allow you to remove all NaN from a list using list comprehension in Python.

from math import nan, isnan list_with_nan= [0, 1, 3, nan, nan, 4, 9, nan] list_without_nan = [x for x in list_with_nan if isnan(x) == False] print(list_without_nan) #Output: [0, 1, 3, 4, 9]

Removing NaN from List with Python filter() Function

The Python filter() function is a built-in function that allows you to process an iterable and extract items that satisfy a given condition.

We can use the Python filter() function to extract all the items in a list of numbers which are not NaN.

Below is some example code showing you how to remove NaN from a list using the filter() function.

from math import nan, isnan list_with_nan= [0, 1, 3, nan, nan, 4, 9, nan] list_without_nan = list(filter(lambda x: isnan(x) == False, list_with_nan)) print(list_without_nan) #Output: [0, 1, 3, 4, 9]

Using the Python numpy Module to Remove NaN from List

We can also remove NaN values using the Python numpy module. The numpy module provides an isnan() function that we can use to check if a value is NaN.

We can use the numpy isnan() function in combination with list comprehension to remove NaN values from a list.

The example below is almost identical to the first example except for we are now using the numpy module.

import numpy as np from numpy import nan list_with_nan= [0, 1, 3, nan, nan, 4, 9, nan] list_without_nan = [x for x in list_with_nan if np.isnan(x) == False] print(list_without_nan) #Output: [0, 1, 3, 4, 9]

Removing NaN from a pandas DataFrame or Series in Python

If you are working with the pandas module in Python, you can use the Python pandas dropna() function to remove NaN values from a pandas DataFrame or column.

To drop the rows or columns with NaN values, you can use the dropna() function in the following ways.

df = df.dropna() #drops rows with missing values df["Column 1"] = df["Column 1"].dropna() #drops rows with missing values in column "Column 1" df = df.dropna(axis=1) #drop columns with missing values

Removing Any Value from List Using Python

In a very similar way, we can remove any value from a list using list comprehension.

For example, if we wanted to remove all empty strings from a list in Python, we could do that easily with list comprehension in Python by adjusting the code above.

list_of_strings = [“This”,””,”is”,”a”,”list”,””,”with”,”empty”,””,”strings”,”.”]
list_without_empty_strings = [x for x in list_of_strings if x != “”]

#Output:
[‘This’, ‘is’, ‘a’, ‘list’, ‘with’, ’empty’, ‘strings’, ‘.’]

Another example is if wanted to remove all zeros from a list, we could do that easily with list comprehension in Python by adjusting the code above.

list_of_numbers = [1,0,4,2,-4,0,0,3,0,-1,0] list_without_zeros = [x for x in list_of_numbers if x != 0] print(list_without_zeros) #Output: [1,4,2,-4,3,-1]

Hopefully this article has been useful for you to learn how to remove NaN from a list in Python.

  • 1. How to Filter Lists in Python
  • 2. Count Spaces in String in Python
  • 3. Using Python to Read File Character by Character
  • 4. Perfect Numbers in Python
  • 5. Generate Random Float Between 0 and 1 Using Python
  • 6. pandas DataFrame size – Get Number of Elements in DataFrame or Series
  • 7. Python Get First Word in String
  • 8. Using Python to Check If List of Words in String
  • 9. PROC MIXED Equivalent in Python for Least Squared Means ANOVA
  • 10. Remove Brackets from String Using Python

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Источник

Remove NaN From List in Python

Remove NaN From List in Python

  1. Remove NaN From the List in Python Using the math.isnan() Method
  2. Remove NaN From the List in Python Using the numpy.isnan() Method
  3. Remove NaN From the List of Strings in Python
  4. Remove NaN From the List in Python Using the pandas.isnull() Method

This tutorial will look into various methods to find and remove the NaN values from the list in Python. The NaN value in programming means Not a Number , which means the variable’s value is not a number.

If a NaN value occurs in an array or a list, it can create problems and errors in the calculations. We will also look into ways to remove the string values nan from the list in this tutorial. We can remove the NaN or ‘nan’ values from the list, by using the following methods.

Remove NaN From the List in Python Using the math.isnan() Method

The math.isnan(value) method takes a number value as input and returns True if the value is a NaN value and returns False otherwise. Therefore we can check if there a NaN value in a list or array of numbers using the math.isnan() method.

We need the math.isnan() method because if float(‘NaN’) == float(‘NaN’) returns False in Python or we can say that two NaN values are not equal in Python. The below example code demonstrates how to use the math.isnan() method to remove the NaN value from the list.

import math  mylist = [1,2,float('nan'),8,6,4,float('nan')] print(mylist) newlist = [x for x in mylist if math.isnan(x) == False] print(newlist) 
[1, 2, nan, 8, 6, 4, nan] [1, 2, 8, 6, 4] 

Remove NaN From the List in Python Using the numpy.isnan() Method

The np.isnan(array) method, takes the array as input and returns True for the corresponding index if it is NaN value and returns False otherwise.

The below example code demonstrates how to remove the NaN values from the list using the numpy.isnan() method:

import numpy as np  mylist = [1,2,float('nan'),8,6,4,float('nan')] print(mylist) newlist = [x for x in mylist if np.isnan(x) == False] print(newlist) 
[1, 2, nan, 8, 6, 4, nan] [1, 2, 8, 6, 4] 

Remove NaN From the List of Strings in Python

Now, let’s suppose that the number list is converted to string type, and we want to check if it contains any NaN values. After converting into the string type, the NaN value becomes a string equal to ‘nan’ and can be easily detected and remove by comparing it with ‘nan’ .

The below example code demonstrates how we can remove the NaN value from the list of string data type:

mylist = [1,2,'nan',8,6,4,'nan'] mylist = [str(x) for x in mylist] print(mylist) newlist = [x for x in mylist if x != 'nan'] print(newlist) 
['1', '2', 'nan', '8', '6', '4', 'nan'] ['1', '2', '8', '6', '4'] 

Remove NaN From the List in Python Using the pandas.isnull() Method

The pandas.isnull(obj) takes a scalar or an array-like obj as input and returns True if the value is equal to NaN , None , or NaT ; otherwise, it returns False .

The example code demonstrates how to use the pandas.isnull() method to remove the NaN values from Python’s list.

import pandas as pd  mylist = [1,2,float('nan'),8,float('nan'),4,float('nan')] print(mylist) newlist = [x for x in mylist if pd.isnull(x) == False] print(newlist) 
[1, 2, nan, 8, nan, 4, nan] [1, 2, 8, 4] 

Now suppose we do not know the type of the list or if the list contains the data of various data types. In this case, we can check and remove the NaN values and ‘nan’ values from the list using the pandas.isnull() method by comparing each value of the list with the ‘nan’ value.

We can use the pandas.isnull() method because, unlike the previously mentioned methods, the pandas.isnull() method does not return an error if the string data type is given as input. Therefore we can use the pandas.isnull() method to remove the NaN and ‘nan’ value from the list or an array in Python.

The below example code demonstrates how to use the pandas.isnull() method and the ‘nan’ value to remove NaN and ‘nan’ values from the list in Python.

import pandas as pd  mylist = ['John',23,'nan','New York',float('nan')] print(mylist) newlist = [x for x in mylist if pd.isnull(x) == False and x != 'nan'] print(newlist) 
['John', 23, 'nan', 'New York', nan] ['John', 23, 'New York'] 

Related Article — Python List

Источник

Оцените статью