🕷️ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 197 (from laksa102)

2. Crawled Status Check

Query:
Response:

3. Robots.txt Check

Query:
Response:

4. Spam/Ban Check

Query:
Response:

5. Seen Status Check

ℹ️ Skipped - page is already crawled

📄
INDEXABLE
✅
CRAWLED
3 days ago
🤖
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH0.1 months ago
History dropPASSisNull(history_drop_reason)No drop reason
Spam/banPASSfh_dont_index != 1 AND ml_spam_score = 0ml_spam_score=0
CanonicalPASSmeta_canonical IS NULL OR = '' OR = src_unparsedNot set

Page Details

PropertyValue
URLhttps://www.pythonpool.com/python-remove-nan-from-list/
Last Crawled2026-04-11 01:01:58 (3 days ago)
First Indexed2021-07-07 04:41:16 (4 years ago)
HTTP Status Code200
Meta Title5 Easy Ways in Python to Remove Nan from List - Python Pool
Meta DescriptionIn Python to remove nan values from list, we can use loop statements or several in built functions from pandas, numpy and math library.
Meta Canonicalnull
Boilerpipe Text
In Python, NaN stands for Not a Number . It is used to represent values that are not present in a dataset or file. It is categorized as a special floating-point value and can only be converted to a float data type. Dealing with NaN type is necessary while working on datasets. There are several ways and built-in functions in Python to remove NaN values. In this article, we shall be looking into such ways in Python to remove nan from the list . Contents Why should we remove NaN values? Why cannot we use np.nan == np.nan? Ways to remove nan from the list 1. Python Remove nan from List Using Numpy’s isnan() function The entire code is: 2. By using Math’s isnan() function The Entire Code is: 3. Python Remove nan from List Using Pandas isnull() function The Entire Code is: 4. Python Remove nan from List Using for loop The entire code is: 5. With list comprehension The syntax of list comprehension is: Popular Right Now Why should we remove NaN values? While performing data analysis, it is important to remove the NaN values. NaN basically represents data that either does not exist or was not collected. Because of missing data, it might mislead the model. It might affect the accuracy and predictions of the model. Hence, it is important to remove nan values. Why cannot we use np.nan == np.nan? When we perform np.nan == np.nan in Python, the output is False as they are not equal. import numpy as np print(np.nan == np.nan) The output is: False The reason behind it is that Python does not consider an equivalence relation between two NaN values. Since NaN values are not defined, two NaN values are not equal. Let us now look at 5 easy and effective ways in Python of removing nan values from a list. Using Numpy’s isnan() function By using Math’s isnan() function Using Pandas isnull() function Using for loop With list comprehension 1. Python Remove nan from List Using Numpy’s isnan() function The isnan() function in numpy will check in a numpy array if the element is NaN or not. It returns a numpy array as an output that contains boolean values. The value will be False where the item is not NaN and True where it is NaN. For that, first, we will have to import the numpy library. import numpy as np from numpy import nan Using np.array() , we shall create a numpy array containing three integer values and three NaN values. my_array = np.array([10, 25, nan, 15,nan,nan] Then, we shall wrap the np.logical_not() function around the output of the isnan() function. We do that because we want the non-NaN values to be printed into the new array. By using logical_not(), it will convert the False values into True and vice – versa. So, for non-NaN values, the value will be True, and for NaN values, it will be false. We shall save the new array into the ‘new_array’ variable. new_array = my_array[np.logical_not(np.isnan(my_array))] print(new_array) The output is: [10. 25. 15.] The entire code is: import numpy as np from numpy import nan my_array = np.array([10, 25, nan, 15,nan,nan]) new_array = my_array[np.logical_not(np.isnan(my_array))] print(new_array) Popular now 2. By using Math’s isnan() function Like numpy, python’s math library also has isnan() function. It will return a boolean value – True if the number is NaN and False if it is not NaN. To use math’s isnan() function, we will first have to import the math library. import math from numpy import nan Then, we shall create a list containing integer values and NaN. my_list = [10, 25, nan, 15,nan,nan] The isnan() in the math library will check for one individual number at a time. So, we shall use list comprehension here to iterate over one item and save the new list into ‘new_list’. new_list = [item for item in my_list if not(math.isnan(item)) == True] print(new_list) The output is: [10, 25, 15] The Entire Code is: import math from numpy import nan my_list = [10, 25, nan, 15,nan,nan] new_list = [item for item in my_list if not(math.isnan(item)) == True] print(new_list) Popular now 3. Python Remove nan from List Using Pandas isnull() function The pandas library in python has a function named isnull() which can be used in python to remove NaN values from the list. First, we will import the pandas library. import pandas as pd from numpy import nan Then we shall use list comprehension here and run a for loop over the list ‘my_list’ . We shall check using not(pd.isnull()) whether the list item is NaN or not and accordingly append that item into a new list named ‘new_list’. my_list = ['Mike', 'Harry', nan, 'Emma',nan,nan] new_list = [item for item in my_list if not(pd.isnull(item)) == True] print(new_list) The output is: ['Mike', 'Harry', 'Emma'] Also, Read | How to Convert Numpy Array to Pandas Dataframe The Entire Code is: import pandas as pd from numpy import nan my_list = ['Mike', 'Harry', nan, 'Emma',nan,nan] new_list = [item for item in my_list if not(pd.isnull(item)) == True] print(new_list) Alternatively, we can also use the isna() function present in pandas similarly. import pandas as pd from numpy import nan my_list = ['Mike', 'Harry', nan, 'Emma',nan,nan] new_list = [item for item in my_list if not(pd.isna(item)) == True] print(new_list) The output is: ['Mike', 'Harry', 'Emma'] 4. Python Remove nan from List Using for loop This is the most basic and effective method for removing nan values from the python list. We will run a for loop over the length of the list. If we encounter a not NaN value, we shall append that value to a new list. The new list will not contain any nan values. First, we will have to import nan from the numpy library. from numpy import nan Now, we shall create a list named my_list. The list contains three string values and three NaN values. We shall also define an empty list named ‘new_list.’ my_list = ['Mike', 'Harry', nan, 'Emma',nan,nan] new_list = [] Now, we shall run a for loop over my_list. Inside the for loop, we shall place an if condition, which will check if the current list item is a NaN value or not. If it is not NaN, then we will append it to the list ‘new_list’. Then at the end, we shall print that list. for item in my_list: if str(item) != 'nan': new_list.append(item) print(new_list) The output is: ['Mike', 'Harry', 'Emma'] The entire code is: from numpy import nan my_list = ['Mike', 'Harry', nan, 'Emma',nan,nan] new_list = [] for item in my_list: if str(item) != 'nan': new_list.append(item) print(new_list) Trending 5. With list comprehension List comprehension is an effective way of generating new sequences from already existing sequences. It is a compact piece of one-line code with which we can loop over a sequence. The syntax of list comprehension is: [expression for item in list if-condition] The expression is the item to be included in the sequence. The expression is followed by a for loop. We can also mention an if condition at the end if required. The code works similarly to using a for loop. The only difference is that it has lesser lines of code and thus more efficient. from numpy import nan my_list = ['Mike', 'Harry', nan, 'Emma',nan,nan] new_list = [item for item in my_list if str(item) != 'nan'] print(new_list) The output is: ['Mike', 'Harry', 'Emma'] Popular now That sums up different ways in python to remove NaN values from the list. If you have any questions in your mind or any thoughts to share, don’t forget to leave them in the comments below. Until next time, Keep Learning! Popular Right Now [Fixed] typeerror can’t compare datetime.datetime to datetime.date [Fixed] nameerror: name Unicode is not defined [Solved] runtimeerror: cuda error: invalid device ordinal [Fixed] typeerror: type numpy.ndarray doesn’t define __round__ method
Markdown
[Skip to content](https://www.pythonpool.com/python-remove-nan-from-list/#content "Skip to content") [![Python Pool](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%201031%20310'%3E%3C/svg%3E)![Python Pool](http://www.pythonpool.com/wp-content/uploads/2020/10/White-Blue-Arrow-Icon-Travel-Logo-1.png)](https://www.pythonpool.com/ "Python Pool") Menu - [Blog](https://www.pythonpool.com/blog/) - [About Us](https://www.pythonpool.com/about-us/) - [Write For Us](https://www.pythonpool.com/guest-post/) - [Contact Us](https://www.pythonpool.com/contact-us/) - [Privacy Policy](https://www.pythonpool.com/privacy-policy/) - [DMCA](https://www.pythonpool.com/dmca/) - [Python Interpreter](https://www.pythonpool.com/python-compiler/) - [Cookies Policy](https://www.pythonpool.com/cookies-policy/) - [Home](https://www.pythonpool.com/) Menu - [Blog](https://www.pythonpool.com/blog/) - [About Us](https://www.pythonpool.com/about-us/) - [Write For Us](https://www.pythonpool.com/guest-post/) - [Contact Us](https://www.pythonpool.com/contact-us/) - [Privacy Policy](https://www.pythonpool.com/privacy-policy/) - [DMCA](https://www.pythonpool.com/dmca/) - [Python Interpreter](https://www.pythonpool.com/python-compiler/) - [Cookies Policy](https://www.pythonpool.com/cookies-policy/) - [Home](https://www.pythonpool.com/) # 5 Easy Ways in Python to Remove Nan from List May 7, 2023 July 7, 2021 ![python remove nan from list](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%201200%20628'%3E%3C/svg%3E) ![python remove nan from list](https://www.pythonpool.com/wp-content/uploads/2021/07/Easy-Ways-in-Python-to-Remove-Nan-from-List.jpg) In Python,**NaNstands for Not a Number**. It is used to represent values that are not present in a dataset or file. It is categorized as a special floating-point value and can only be converted to a float data type. Dealing with NaN type is necessary while working on datasets. There are several ways and built-in functions in Python to remove NaN values. In this article, we shall be looking into such ways in Python to remove nan from the *list*. Contents [Toggle](https://www.pythonpool.com/python-remove-nan-from-list/) - [Why should we remove NaN values?](https://www.pythonpool.com/python-remove-nan-from-list/#Why_should_we_remove_NaN_values) - [Why cannot we use np.nan == np.nan?](https://www.pythonpool.com/python-remove-nan-from-list/#Why_cannot_we_use_npnan_npnan) - [Ways to remove nan from the list](https://www.pythonpool.com/python-remove-nan-from-list/#Ways_to_remove_nan_from_the_list) - [1\. Python Remove nan from List Using Numpy’s isnan() function](https://www.pythonpool.com/python-remove-nan-from-list/#1_Python_Remove_nan_from_List_Using_Numpys_isnan_function) - [The entire code is:](https://www.pythonpool.com/python-remove-nan-from-list/#The_entire_code_is) - [2\. By using Math’s isnan() function](https://www.pythonpool.com/python-remove-nan-from-list/#2_By_using_Maths_isnan_function) - [The Entire Code is:](https://www.pythonpool.com/python-remove-nan-from-list/#The_Entire_Code_is) - [3\. Python Remove nan from List Using Pandas isnull() function](https://www.pythonpool.com/python-remove-nan-from-list/#3_Python_Remove_nan_from_List_Using_Pandas_isnull_function) - [The Entire Code is:](https://www.pythonpool.com/python-remove-nan-from-list/#The_Entire_Code_is-2) - [4\. Python Remove nan from List Using for loop](https://www.pythonpool.com/python-remove-nan-from-list/#4_Python_Remove_nan_from_List_Using_for_loop) - [The entire code is:](https://www.pythonpool.com/python-remove-nan-from-list/#The_entire_code_is-2) - [5\. With list comprehension](https://www.pythonpool.com/python-remove-nan-from-list/#5_With_list_comprehension) - [The syntax of list comprehension is:](https://www.pythonpool.com/python-remove-nan-from-list/#The_syntax_of_list_comprehension_is) - [Popular Right Now](https://www.pythonpool.com/python-remove-nan-from-list/#Popular_Right_Now) ## Why should we remove NaN values? **While performing data analysis, it is important to remove the NaN values. NaN basically represents data that either does not exist or was not collected. Because of missing data, it might mislead the model. It might affect the accuracy and predictions of the model. Hence, it is important to remove nan values.** ## Why cannot we use np.nan == np.nan? When we perform np.nan == np.nan in Python, the output is False as they are not equal. ``` import numpy as np print(np.nan == np.nan) ``` **The output is:** ``` False ``` The reason behind it is that Python does not consider an equivalence relation between two NaN values. Since NaN values are not defined, two NaN values are not equal. ## Ways to remove nan from the list **Let us now look at 5 easy and effective ways in Python of removing nan values from a list.** 1. **Using Numpy’s isnan() function** 2. **By using Math’s isnan() function** 3. **Using Pandas isnull() function** 4. **Using for loop** 5. **With list comprehension** ## 1\. Python Remove nan from List Using Numpy’s isnan() function The *isnan()* function in numpy will check in a numpy array if the element is NaN or not. It returns a numpy array as an output that contains boolean values. The value will be False where the item is not NaN and True where it is NaN. For that, first, we will have to import the numpy library. ``` import numpy as np from numpy import nan ``` Using *np.array()*, we shall create a numpy array containing three integer values and three NaN values. ``` my_array = np.array([10, 25, nan, 15,nan,nan] ``` Then, we shall wrap the *np.logical\_not()* function around the output of the *isnan()* function. We do that because we want the non-NaN values to be printed into the new array. By using logical\_not(), it will convert the False values into True and vice – versa. So, for non-NaN values, the value will be True, and for NaN values, it will be false. We shall save the new array into the *‘new\_array’* variable. ``` new_array = my_array[np.logical_not(np.isnan(my_array))] print(new_array) ``` **The output is:** ``` [10. 25. 15.] ``` ### The entire code is: ``` import numpy as np from numpy import nan my_array = np.array([10, 25, nan, 15,nan,nan]) new_array = my_array[np.logical_not(np.isnan(my_array))] print(new_array) ``` Popular now [\[Fixed\] typeerror can’t compare datetime.datetime to datetime.date](https://www.pythonpool.com/fixed-typeerror-cant-compare-datetime-datetime-to-datetime-date/) ## 2\. By using Math’s isnan() function Like numpy, python’s math library also has *isnan()* function. It will return a [boolean](https://en.wikipedia.org/wiki/Boolean) value – True if the number is NaN and False if it is not NaN. To use math’s *isnan()* function, we will first have to import the math library. ``` import math from numpy import nan ``` Then, we shall create a list containing integer values and NaN. ``` my_list = [10, 25, nan, 15,nan,nan] ``` The *isnan()* in the math library will check for one individual number at a time. So, we shall use list comprehension here to [iterate over one item](https://www.pythonpool.com/python-iterate-through-list/) and save the new list into *‘new\_list’.* ``` new_list = [item for item in my_list if not(math.isnan(item)) == True] print(new_list) ``` **The output is:** ``` [10, 25, 15] ``` ### The Entire Code is: ``` import math from numpy import nan my_list = [10, 25, nan, 15,nan,nan] new_list = [item for item in my_list if not(math.isnan(item)) == True] print(new_list) ``` Popular now [\[Fixed\] nameerror: name Unicode is not defined](https://www.pythonpool.com/fixed-nameerror-name-unicode-is-not-defined/) ## 3\. Python Remove nan from List Using Pandas isnull() function The pandas library in python has a function named *isnull()* which can be used in python to remove NaN values from the list. First, we will import the pandas library. ``` import pandas as pd from numpy import nan ``` Then we shall use list comprehension here and run a for loop over the list *‘my\_list’*. We shall check using *not(pd.isnull())* whether the list item is NaN or not and accordingly append that item into a new list named *‘new\_list’.* ``` my_list = ['Mike', 'Harry', nan, 'Emma',nan,nan] new_list = [item for item in my_list if not(pd.isnull(item)) == True] print(new_list) ``` **The output is:** ``` ['Mike', 'Harry', 'Emma'] ``` **Also, Read \|** [How to Convert Numpy Array to Pandas Dataframe](https://www.pythonpool.com/numpy-array-to-pandas-dataframe/) ### The Entire Code is: ``` import pandas as pd from numpy import nan my_list = ['Mike', 'Harry', nan, 'Emma',nan,nan] new_list = [item for item in my_list if not(pd.isnull(item)) == True] print(new_list) ``` Alternatively, we can also use the *isna()* function present in pandas similarly. ``` import pandas as pd from numpy import nan my_list = ['Mike', 'Harry', nan, 'Emma',nan,nan] new_list = [item for item in my_list if not(pd.isna(item)) == True] print(new_list) ``` **The output is:** ``` ['Mike', 'Harry', 'Emma'] ``` *** ## 4\. Python Remove nan from List Using for loop This is the most basic and effective method for removing nan values from the python list. We will run a for loop over the length of the list. If we encounter a not NaN value, we shall append that value to a new list. The new list will not contain any nan values. First, we will have to import nan from the numpy library. ``` from numpy import nan ``` Now, we shall create a list named *my\_list.* The list contains three string values and three NaN values. We shall also define an empty list named *‘new\_list.’* ``` my_list = ['Mike', 'Harry', nan, 'Emma',nan,nan] new_list = [] ``` Now, we shall run a for loop over *my\_list.* Inside the for loop, we shall place an if condition, which will check if the current list item is a NaN value or not. If it is not NaN, then we will append it to the list ‘new\_list’. Then at the end, we shall print that list. ``` for item in my_list: if str(item) != 'nan': new_list.append(item) print(new_list) ``` **The output is:** ``` ['Mike', 'Harry', 'Emma'] ``` ### **The entire code is:** ``` from numpy import nan my_list = ['Mike', 'Harry', nan, 'Emma',nan,nan] new_list = [] for item in my_list: if str(item) != 'nan': new_list.append(item) print(new_list) ``` Trending [\[Solved\] runtimeerror: cuda error: invalid device ordinal](https://www.pythonpool.com/solved-runtimeerror-cuda-error-invalid-device-ordinal/) ## 5\. With list comprehension List comprehension is an effective way of generating new sequences from already existing sequences. It is a compact piece of one-line code with which we can loop over a sequence. ### The syntax of list comprehension is: ``` [expression for item in list if-condition] ``` The expression is the item to be included in the sequence. The expression is followed by a for loop. We can also mention an if condition at the end if required. The code works similarly to using a for loop. The only difference is that it has lesser lines of code and thus more efficient. ``` from numpy import nan my_list = ['Mike', 'Harry', nan, 'Emma',nan,nan] new_list = [item for item in my_list if str(item) != 'nan'] print(new_list) ``` **The output is:** ``` ['Mike', 'Harry', 'Emma'] ``` Popular now [\[Fixed\] typeerror: type numpy.ndarray doesn’t define \_\_round\_\_ method](https://www.pythonpool.com/fixed-typeerror-type-numpy-ndarray-doesnt-define-__round__-method/) That sums up different ways in python to remove NaN values from the list. If you have any questions in your mind or any thoughts to share, don’t forget to leave them in the comments below. *Until next time, Keep Learning\!* ## Popular Right Now - [\[Fixed\] typeerror can’t compare datetime.datetime to datetime.date](https://www.pythonpool.com/fixed-typeerror-cant-compare-datetime-datetime-to-datetime-date/) - [\[Fixed\] nameerror: name Unicode is not defined](https://www.pythonpool.com/fixed-nameerror-name-unicode-is-not-defined/) - [\[Solved\] runtimeerror: cuda error: invalid device ordinal](https://www.pythonpool.com/solved-runtimeerror-cuda-error-invalid-device-ordinal/) - [\[Fixed\] typeerror: type numpy.ndarray doesn’t define \_\_round\_\_ method](https://www.pythonpool.com/fixed-typeerror-type-numpy-ndarray-doesnt-define-__round__-method/) [Find Out What is Run Length Encoding in Python](https://www.pythonpool.com/run-length-encoding-python/) [Python class Vs module: Differences and Comparison](https://www.pythonpool.com/python-class-vs-module/) Subscribe [Login](https://www.pythonpool.com/link2access/?redirect_to=https%3A%2F%2Fwww.pythonpool.com%2Fpython-remove-nan-from-list%2F) 0 Comments Oldest Newest Most Voted Inline Feedbacks View all comments ## About us Python Pool is a platform where you can learn and become an expert in every aspect of Python programming language as well as in AI, ML, and Data Science. ## Quick Links - [AI](https://www.pythonpool.com/category/ai/) - [Algorithm](https://www.pythonpool.com/category/algorithm/) - [Books](https://www.pythonpool.com/category/books/) - [Career](https://www.pythonpool.com/category/career/) - [Comparison](https://www.pythonpool.com/category/comparison/) - [Data Science](https://www.pythonpool.com/category/data-science/) - [Error](https://www.pythonpool.com/category/error/) - [Flask](https://www.pythonpool.com/category/flask/) - [How to](https://www.pythonpool.com/category/how-to/) - [IDE & Editor](https://www.pythonpool.com/category/ide-editor/) - [Jupyter](https://www.pythonpool.com/category/jupyter/) - [Learning](https://www.pythonpool.com/category/learning/) - [Machine Learning](https://www.pythonpool.com/category/machine-learning/) - [Matplotlib](https://www.pythonpool.com/category/matplotlib/) - [Module](https://www.pythonpool.com/category/module/) - [News](https://www.pythonpool.com/category/news/) - [Numpy](https://www.pythonpool.com/category/numpy/) - [OpenCV](https://www.pythonpool.com/category/opencv/) - [Pandas](https://www.pythonpool.com/category/pandas/) - [Programs](https://www.pythonpool.com/category/programs/) - [Project](https://www.pythonpool.com/category/project/) - [PyQT](https://www.pythonpool.com/category/pyqt/) - [PySpark](https://www.pythonpool.com/category/pyspark/) - [Questions](https://www.pythonpool.com/category/questions/) - [Review](https://www.pythonpool.com/category/review/) - [Software](https://www.pythonpool.com/category/software/) - [Tensorflow](https://www.pythonpool.com/category/tensorflow/) - [Tkinter](https://www.pythonpool.com/category/tkinter/) - [Tutorials](https://www.pythonpool.com/category/tutorials/) - [Uncategorized](https://www.pythonpool.com/category/uncategorized/) ## Pages - [Cookies Policy](https://www.pythonpool.com/cookies-policy/) - [DMCA](https://www.pythonpool.com/dmca/) - [Privacy Policy](https://www.pythonpool.com/privacy-policy/) © 2026 Python Pool • Built with [GeneratePress](https://generatepress.com/) wpDiscuz Insert
Readable Markdown
In Python,**NaNstands for Not a Number**. It is used to represent values that are not present in a dataset or file. It is categorized as a special floating-point value and can only be converted to a float data type. Dealing with NaN type is necessary while working on datasets. There are several ways and built-in functions in Python to remove NaN values. In this article, we shall be looking into such ways in Python to remove nan from the *list*. Contents - [Why should we remove NaN values?](https://www.pythonpool.com/python-remove-nan-from-list/#Why_should_we_remove_NaN_values) - [Why cannot we use np.nan == np.nan?](https://www.pythonpool.com/python-remove-nan-from-list/#Why_cannot_we_use_npnan_npnan) - [Ways to remove nan from the list](https://www.pythonpool.com/python-remove-nan-from-list/#Ways_to_remove_nan_from_the_list) - [1\. Python Remove nan from List Using Numpy’s isnan() function](https://www.pythonpool.com/python-remove-nan-from-list/#1_Python_Remove_nan_from_List_Using_Numpys_isnan_function) - [The entire code is:](https://www.pythonpool.com/python-remove-nan-from-list/#The_entire_code_is) - [2\. By using Math’s isnan() function](https://www.pythonpool.com/python-remove-nan-from-list/#2_By_using_Maths_isnan_function) - [The Entire Code is:](https://www.pythonpool.com/python-remove-nan-from-list/#The_Entire_Code_is) - [3\. Python Remove nan from List Using Pandas isnull() function](https://www.pythonpool.com/python-remove-nan-from-list/#3_Python_Remove_nan_from_List_Using_Pandas_isnull_function) - [The Entire Code is:](https://www.pythonpool.com/python-remove-nan-from-list/#The_Entire_Code_is-2) - [4\. Python Remove nan from List Using for loop](https://www.pythonpool.com/python-remove-nan-from-list/#4_Python_Remove_nan_from_List_Using_for_loop) - [The entire code is:](https://www.pythonpool.com/python-remove-nan-from-list/#The_entire_code_is-2) - [5\. With list comprehension](https://www.pythonpool.com/python-remove-nan-from-list/#5_With_list_comprehension) - [The syntax of list comprehension is:](https://www.pythonpool.com/python-remove-nan-from-list/#The_syntax_of_list_comprehension_is) - [Popular Right Now](https://www.pythonpool.com/python-remove-nan-from-list/#Popular_Right_Now) ## Why should we remove NaN values? **While performing data analysis, it is important to remove the NaN values. NaN basically represents data that either does not exist or was not collected. Because of missing data, it might mislead the model. It might affect the accuracy and predictions of the model. Hence, it is important to remove nan values.** ## Why cannot we use np.nan == np.nan? When we perform np.nan == np.nan in Python, the output is False as they are not equal. ``` import numpy as np print(np.nan == np.nan) ``` **The output is:** ``` False ``` The reason behind it is that Python does not consider an equivalence relation between two NaN values. Since NaN values are not defined, two NaN values are not equal. **Let us now look at 5 easy and effective ways in Python of removing nan values from a list.** 1. **Using Numpy’s isnan() function** 2. **By using Math’s isnan() function** 3. **Using Pandas isnull() function** 4. **Using for loop** 5. **With list comprehension** ## 1\. Python Remove nan from List Using Numpy’s isnan() function The *isnan()* function in numpy will check in a numpy array if the element is NaN or not. It returns a numpy array as an output that contains boolean values. The value will be False where the item is not NaN and True where it is NaN. For that, first, we will have to import the numpy library. ``` import numpy as np from numpy import nan ``` Using *np.array()*, we shall create a numpy array containing three integer values and three NaN values. ``` my_array = np.array([10, 25, nan, 15,nan,nan] ``` Then, we shall wrap the *np.logical\_not()* function around the output of the *isnan()* function. We do that because we want the non-NaN values to be printed into the new array. By using logical\_not(), it will convert the False values into True and vice – versa. So, for non-NaN values, the value will be True, and for NaN values, it will be false. We shall save the new array into the *‘new\_array’* variable. ``` new_array = my_array[np.logical_not(np.isnan(my_array))] print(new_array) ``` **The output is:** ``` [10. 25. 15.] ``` ### The entire code is: ``` import numpy as np from numpy import nan my_array = np.array([10, 25, nan, 15,nan,nan]) new_array = my_array[np.logical_not(np.isnan(my_array))] print(new_array) ``` Popular now ## 2\. By using Math’s isnan() function Like numpy, python’s math library also has *isnan()* function. It will return a [boolean](https://en.wikipedia.org/wiki/Boolean) value – True if the number is NaN and False if it is not NaN. To use math’s *isnan()* function, we will first have to import the math library. ``` import math from numpy import nan ``` Then, we shall create a list containing integer values and NaN. ``` my_list = [10, 25, nan, 15,nan,nan] ``` The *isnan()* in the math library will check for one individual number at a time. So, we shall use list comprehension here to [iterate over one item](https://www.pythonpool.com/python-iterate-through-list/) and save the new list into *‘new\_list’.* ``` new_list = [item for item in my_list if not(math.isnan(item)) == True] print(new_list) ``` **The output is:** ``` [10, 25, 15] ``` ### The Entire Code is: ``` import math from numpy import nan my_list = [10, 25, nan, 15,nan,nan] new_list = [item for item in my_list if not(math.isnan(item)) == True] print(new_list) ``` Popular now ## 3\. Python Remove nan from List Using Pandas isnull() function The pandas library in python has a function named *isnull()* which can be used in python to remove NaN values from the list. First, we will import the pandas library. ``` import pandas as pd from numpy import nan ``` Then we shall use list comprehension here and run a for loop over the list *‘my\_list’*. We shall check using *not(pd.isnull())* whether the list item is NaN or not and accordingly append that item into a new list named *‘new\_list’.* ``` my_list = ['Mike', 'Harry', nan, 'Emma',nan,nan] new_list = [item for item in my_list if not(pd.isnull(item)) == True] print(new_list) ``` **The output is:** ``` ['Mike', 'Harry', 'Emma'] ``` **Also, Read \|** [How to Convert Numpy Array to Pandas Dataframe](https://www.pythonpool.com/numpy-array-to-pandas-dataframe/) ### The Entire Code is: ``` import pandas as pd from numpy import nan my_list = ['Mike', 'Harry', nan, 'Emma',nan,nan] new_list = [item for item in my_list if not(pd.isnull(item)) == True] print(new_list) ``` Alternatively, we can also use the *isna()* function present in pandas similarly. ``` import pandas as pd from numpy import nan my_list = ['Mike', 'Harry', nan, 'Emma',nan,nan] new_list = [item for item in my_list if not(pd.isna(item)) == True] print(new_list) ``` **The output is:** ``` ['Mike', 'Harry', 'Emma'] ``` *** ## 4\. Python Remove nan from List Using for loop This is the most basic and effective method for removing nan values from the python list. We will run a for loop over the length of the list. If we encounter a not NaN value, we shall append that value to a new list. The new list will not contain any nan values. First, we will have to import nan from the numpy library. ``` from numpy import nan ``` Now, we shall create a list named *my\_list.* The list contains three string values and three NaN values. We shall also define an empty list named *‘new\_list.’* ``` my_list = ['Mike', 'Harry', nan, 'Emma',nan,nan] new_list = [] ``` Now, we shall run a for loop over *my\_list.* Inside the for loop, we shall place an if condition, which will check if the current list item is a NaN value or not. If it is not NaN, then we will append it to the list ‘new\_list’. Then at the end, we shall print that list. ``` for item in my_list: if str(item) != 'nan': new_list.append(item) print(new_list) ``` **The output is:** ``` ['Mike', 'Harry', 'Emma'] ``` ### **The entire code is:** ``` from numpy import nan my_list = ['Mike', 'Harry', nan, 'Emma',nan,nan] new_list = [] for item in my_list: if str(item) != 'nan': new_list.append(item) print(new_list) ``` Trending ## 5\. With list comprehension List comprehension is an effective way of generating new sequences from already existing sequences. It is a compact piece of one-line code with which we can loop over a sequence. ### The syntax of list comprehension is: ``` [expression for item in list if-condition] ``` The expression is the item to be included in the sequence. The expression is followed by a for loop. We can also mention an if condition at the end if required. The code works similarly to using a for loop. The only difference is that it has lesser lines of code and thus more efficient. ``` from numpy import nan my_list = ['Mike', 'Harry', nan, 'Emma',nan,nan] new_list = [item for item in my_list if str(item) != 'nan'] print(new_list) ``` **The output is:** ``` ['Mike', 'Harry', 'Emma'] ``` Popular now That sums up different ways in python to remove NaN values from the list. If you have any questions in your mind or any thoughts to share, don’t forget to leave them in the comments below. *Until next time, Keep Learning\!* ## Popular Right Now - [\[Fixed\] typeerror can’t compare datetime.datetime to datetime.date](https://www.pythonpool.com/fixed-typeerror-cant-compare-datetime-datetime-to-datetime-date/) - [\[Fixed\] nameerror: name Unicode is not defined](https://www.pythonpool.com/fixed-nameerror-name-unicode-is-not-defined/) - [\[Solved\] runtimeerror: cuda error: invalid device ordinal](https://www.pythonpool.com/solved-runtimeerror-cuda-error-invalid-device-ordinal/) - [\[Fixed\] typeerror: type numpy.ndarray doesn’t define \_\_round\_\_ method](https://www.pythonpool.com/fixed-typeerror-type-numpy-ndarray-doesnt-define-__round__-method/)
Shard197 (laksa)
Root Hash10768594352196822397
Unparsed URLcom,pythonpool!www,/python-remove-nan-from-list/ s443