🕷️ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 35 (from laksa086)

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
1 month ago
🤖
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH1.7 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://pythonguides.com/remove-nan-values-from-a-list-in-python/
Last Crawled2026-02-19 03:04:12 (1 month ago)
First Indexed2024-02-13 07:33:46 (2 years ago)
HTTP Status Code200
Meta TitleHow To Remove NaN Values From A List In Python
Meta DescriptionLearn how to remove NaN values from a list in Python using list comprehension, math.isnan(), NumPy, pandas, and filter methods with practical examples.
Meta Canonicalnull
Boilerpipe Text
While cleaning a dataset for a project, I ran into an issue where my Python list had a mix of numbers and NaN values. If you’ve worked with real-world data in the US, say, sales reports, healthcare data, or survey results, you know how common missing values can be. The problem is simple: NaN (Not a Number) values can break calculations and give unexpected results. Unfortunately, Python lists don’t have a built-in method to directly filter them out . I’ve tried different approaches, and in this tutorial, I’ll show you the most effective methods I use to remove NaN values from a list in Python . Table of Contents Methods to Remove NaN Values from a List in Python 1: Use the For Loop in Python 2: Use List Comprehension in Python 3: Use the Filter Method in Python 4. Use the isnan() math Module in Python 5: Remove NaN from the Numpy array 6. Remove NaN from the List in Pandas Let me show you the methods to remove NaN values from a list in Python. 1: Use the For Loop in Python The for loop in Python is a common and effective way to remove NaN values from a list. original_data = [1, 2, 3, 4, float('nan'), 6] cleaned_data = [] for x in original_data: if x == x: cleaned_data.append(x) print(cleaned_data) In this code, we iterate through each element in the original_data list in Python. The condition if x == x checks if the element is not NaN (since NaN does not equal itself) If the condition is true, we append the element to the cleaned_data list in Python. # When it iterates to NaN == NaN, then it will return False if x == x: cleaned_data.append(x) Output [1, 2, 3, 4, 6] You can refer to the screenshot below to see the output. This method removes NaN values from a list by using a for loop and the condition x == x, which filters out NaN since it is not equal to itself . 2: Use List Comprehension in Python List comprehension is a concise and elegant way to create lists in Python. It offers a more compact syntax compared to loops. In the context of removing NaN values from a list. employee_age = [42, 35, float('nan'), 26, float('nan'), 28] filtered_list = [x for x in employee_age if x == x] print(filtered_list) We use the same logic we used in the previous example, using list comprehension in Python with fewer lines of code and a faster approach. Output [42, 35, 26, 28] You can refer to the screenshot below to see the output. This method removes NaN values efficiently using list comprehension , providing a shorter and faster alternative to a traditional loop. 3: Use the Filter Method in Python The filter() method is a built-in function of Python that applies a specified function to each item of the collection and returns an iterator containing only the items for which the function evaluates to True. Code week_sales = [5000, 8000, float('nan'), 2000, float('nan'), 3000, 9000] filtered_list = list(filter(lambda x: x == x, week_sales )) print(filtered_list) The filter() method in Python removes NaN values from the week_sales list by applying a lambda function that checks each element for equality with itself. Output [5000, 8000, 2000, 3000, 9000] You can refer to the screenshot below to see the output. Since NaN does not equal itself, the lambda function in Python filters out NaN values. Then, filtered_list is converted back to a list for further processing . 4. Use the isnan() math Module in Python To remove NaN values from the Python list, we can use the isnan() function, which is an inbuilt method of the math module in Python. It will check all the elements and return True, where it will find NaN. from math import isnan original_list = [1, 2, float('nan'), 4, float('nan'), 6] cleaned_list = [] for i in original_list: if not isnan(i): cleaned_list+=[i] print(cleaned_list) I’ve initialized the original_list list in Python with numerical values, including NaN values that float(‘nan’) represents. Then, iterate through each element i in original_list. The isnan() function in Python is used to check if i is not a NaN value. Output [1, 2, 4, 6] You can refer to the screenhsot below to see the output. This method uses Python’s math.isnan() for a clear and reliable way to detect and remove NaN values from a list. 5: Remove NaN from the Numpy array To remove NaN values from a list from Python NumPy array , we will use the isnan() method of the numpy library to check whether the element is NaN or not, and it will return True or False based on whether the element is NaN. If an element is NaN in the array, it will return True. Code import numpy as np from numpy import nan data = np.array([5, 12, nan, 7,nan,9]) filtered_data = data[np.logical_not(np.isnan(data))] print(filtered_data) We used NumPy’s isnan() function in Python to identify NaN values within the array data. The np.logical_not() function is used to negate this result. Output [ 5. 12. 7. 9.] You can refer to the screenshot below to see the output. This method efficiently removes NaN values from a NumPy array using np.isnan() with np.logical_not() for clean, numeric-only data. 6. Remove NaN from the List in Pandas To remove NaN from a list using Pandas, there is one inbuilt function in Python called dropna(), which will directly remove the NaN values from the series in Python, and then you can convert it to a list using the tolist() method. Here is an instance to remove NaN values from a list in Python using the pandas library: Code import pandas as pd original_list = [1, 2, float('nan'), 4, float('nan'), 6] series = pd.Series(original_list) cleaned_list = series.dropna().tolist() print(cleaned_list) We’ve used the dropna() function in Python Pandas to remove any NaN values from the series of original lists, resulting in a cleaned_list. Finally, the tolist() function in Python converts the cleaned series into a list format. Output [1.0, 2.0, 4.0, 6.0] You can refer to the screenshot below to see the output. This method removes NaN values from a list using Pandas’ dropna() and converts the cleaned series back into a list with tolist(). Here, I’ve covered all the different ways to remove the NaN value from the list in Python using for loop, list comprehension, filter method, isnan() method from math module, isnan() method from numpy, and dropna() method from Pandas. Each method offers its advantages and can be chosen based on specific requirements. You may like to read other Python tutorials: Find the Mean of a List in Python Sum a List in Python Without the Sum Function Python Sort List Alphabetically Sum Elements in a List in Python I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile .
Markdown
[Skip to content](https://pythonguides.com/remove-nan-values-from-a-list-in-python/#content "Skip to content") [![Python Guides](https://pythonguides.com/wp-content/uploads/2022/10/PythonGuides-Logo-1.svg)](https://pythonguides.com/) [![Python Guides](https://pythonguides.com/wp-content/uploads/2022/10/PythonGuides-Logo-1.svg)](https://pythonguides.com/ "Python Guides") Menu - [Home](https://pythonguides.com/) - [Python](https://pythonguides.com/python-programming-tutorials/) - [Data Types](https://pythonguides.com/data-types/) - [Operators](https://pythonguides.com/operators/) - [IFs and Loops](https://pythonguides.com/conditional-statements-and-loops/) - [Functions](https://pythonguides.com/functions/) - [File Handling](https://pythonguides.com/file-handling/) - [Exception Handling](https://pythonguides.com/exception-handling/) - [Dictionary](https://pythonguides.com/dictionaries/) - [Lists](https://pythonguides.com/lists/) - [Tuples](https://pythonguides.com/tuples/) - [Sets](https://pythonguides.com/sets/) - [Arrays](https://pythonguides.com/arrays/) - [OOPS](https://pythonguides.com/object-oriented-programming/) - [Libraries](https://pythonguides.com/remove-nan-values-from-a-list-in-python/) - [Matplotlib](https://pythonguides.com/matplotlib-in-python/) - [Django](https://pythonguides.com/python-django-tutorials/) - [Pandas](https://pythonguides.com/pandas/) - [Tensorflow](https://pythonguides.com/python-tensorflow-tutorials/) - [NumPy](https://pythonguides.com/numpy-tutorials/) - [TKinter](https://pythonguides.com/tkinter/) - [PyTorch](https://pythonguides.com/pytorch/) - [Turtle](https://pythonguides.com/turtle/) - [Scikit-Learn](https://pythonguides.com/scikit-learn/) - [SciPy](https://pythonguides.com/scipy/) - [PyQt6](https://pythonguides.com/pyqt6/) - [Keras](https://pythonguides.com/keras/) - [Typescript](https://pythonguides.com/typescript-basics/) - [TypeScript Basics](https://pythonguides.com/typescript-basics/) - [TypeScript Functions](https://pythonguides.com/typescript-functions/) - [Typescript Arrays](https://pythonguides.com/typescript-arrays/) - [TypeScript Strings](https://pythonguides.com/typescript-strings/) - [TypeScript Dates](https://pythonguides.com/typescript-date/) - [TypeScript Enums](https://pythonguides.com/typescript-enums/) - [React JS](https://pythonguides.com/reactjs/) - [Machine Learning](https://pythonguides.com/machine-learning/) - [FREE ML Training](https://pythonguides.com/python-and-machine-learning-training-course/) - [JS](https://pythonguides.com/javascript-and-jquery/) - [FREE eBook](https://pythonguides.com/free-ebook/) - [Free Online Tools](https://pythonguides.com/free-online-tools/) - [JPG to PNG Converter Online](https://pythonguides.com/jpg-to-png-converter/) - [Free Payslip Generator](https://pythonguides.com/free-payslip-generator/) - [Convert Case Tool Online](https://pythonguides.com/convert-case-tool-online/) - [USD to INR Converter Online FREEE](https://pythonguides.com/usd-to-inr-converter/) - [Free Online Resignation Email Generator](https://pythonguides.com/free-online-resignation-email-generator/) - [FREE Cryptographically Secure Password Generator](https://pythonguides.com/free-cryptographically-secure-password-generator-online/) - [FREE Images to PDF Converter Online](https://pythonguides.com/free-images-to-pdf-converter-online/) - [FREE QR Code Generator for Digital Business Card](https://pythonguides.com/free-qr-code-generator-for-digital-business-card/) - [Blogs](https://pythonguides.com/blogs/) # How to Remove NaN Values from a List in Python September 1, 2025 by [Bijay Kumar](https://pythonguides.com/author/fewlines4biju/ "View all posts by Bijay Kumar") [DOWNLOAD 51 PYTHON PROGRAMS PDF FREE](https://pythonguides.com/remove-nan-values-from-a-list-in-python/#elementor-action%3Aaction%3Dpopup%3Aopen%26settings%3DeyJpZCI6IjYwNTA2IiwidG9nZ2xlIjpmYWxzZX0%3D) While cleaning a dataset for a project, I ran into an issue where my Python list had a mix of numbers and `NaN` values. If you’ve worked with real-world data in the US, say, sales reports, healthcare data, or survey results, you know how common missing values can be. The problem is simple: NaN (Not a Number) values can break calculations and give unexpected results. Unfortunately, Python lists don’t have a built-in method to directly [filter them out](https://pythonguides.com/filter-not-in-django/). I’ve tried different approaches, and in this tutorial, I’ll show you the most effective methods I use to **remove NaN values from a list in Python**. Table of Contents [Toggle](https://pythonguides.com/remove-nan-values-from-a-list-in-python/) - [Methods to Remove NaN Values from a List in Python](https://pythonguides.com/remove-nan-values-from-a-list-in-python/#Methods_to_Remove_NaN_Values_from_a_List_in_Python) - [1: Use the For Loop in Python](https://pythonguides.com/remove-nan-values-from-a-list-in-python/#1_Use_the_For_Loop_in_Python) - [2: Use List Comprehension in Python](https://pythonguides.com/remove-nan-values-from-a-list-in-python/#2_Use_List_Comprehension_in_Python) - [3: Use the Filter Method in Python](https://pythonguides.com/remove-nan-values-from-a-list-in-python/#3_Use_the_Filter_Method_in_Python) - [4\. Use the isnan() math Module in Python](https://pythonguides.com/remove-nan-values-from-a-list-in-python/#4_Use_the_isnan_math_Module_in_Python) - [5: Remove NaN from the Numpy array](https://pythonguides.com/remove-nan-values-from-a-list-in-python/#5_Remove_NaN_from_the_Numpy_array) - [6\. Remove NaN from the List in Pandas](https://pythonguides.com/remove-nan-values-from-a-list-in-python/#6_Remove_NaN_from_the_List_in_Pandas) ## Methods to Remove NaN Values from a List in Python Let me show you the methods to remove NaN values from a list in Python. ### 1: Use the For Loop in Python The [for loop in Python](https://pythonguides.com/for-loop-vs-while-loop-in-python/) is a common and effective way to remove NaN values from a list. ``` original_data = [1, 2, 3, 4, float('nan'), 6] cleaned_data = [] for x in original_data: if x == x: cleaned_data.append(x) print(cleaned_data) ``` In this code, we [iterate through each element](https://pythonguides.com/iterate-through-a-string-in-python/) in the original\_data list in Python. The condition if x == x checks if the element is not NaN (since NaN does not equal itself) If the condition is true, we append the element to the cleaned\_data list in Python. ``` # When it iterates to NaN == NaN, then it will return False if x == x: cleaned_data.append(x) ``` **Output** ``` [1, 2, 3, 4, 6] ``` You can refer to the screenshot below to see the output. ![How to remove nan from a list in python](https://pythonguides.com/wp-content/uploads/2024/01/How-to-remove-nan-from-a-list-in-python-1024x388.jpg) This method removes NaN values from a list by using a for loop and the condition x == x, which filters out NaN since it is [not equal to itself](https://pythonguides.com/check-array-equality-in-typescript/). ### 2: Use List Comprehension in Python List comprehension is a concise and elegant way to create lists in Python. It offers a more compact syntax compared to loops. In the context of removing NaN values from a list. ``` employee_age = [42, 35, float('nan'), 26, float('nan'), 28] filtered_list = [x for x in employee_age if x == x] print(filtered_list) ``` We use the same logic we used in the previous example, using list comprehension in Python with fewer lines of code and a faster approach. **Output** ``` [42, 35, 26, 28] ``` You can refer to the screenshot below to see the output. ![remove NaN value in python](https://pythonguides.com/wp-content/uploads/2024/01/remove-NaN-value-in-python.jpg) This method removes NaN values efficiently using [list comprehension](https://pythonguides.com/python-list-comprehension-using-if-else/), providing a shorter and faster alternative to a traditional loop. ### 3: Use the Filter Method in Python The filter() method is a built-in function of Python that applies a specified function to each item of the collection and returns an iterator containing only the items for which the function evaluates to True. **Code** ``` week_sales = [5000, 8000, float('nan'), 2000, float('nan'), 3000, 9000] filtered_list = list(filter(lambda x: x == x, week_sales )) print(filtered_list) ``` The filter() method in Python removes NaN values from the week\_sales list by applying a lambda function that checks each element for equality with itself. **Output** ``` [5000, 8000, 2000, 3000, 9000] ``` You can refer to the screenshot below to see the output. ![drop nan values from the list in python](https://pythonguides.com/wp-content/uploads/2024/01/drop-nan-values-from-the-list-in-python.jpg) Since NaN does not equal itself, the lambda function in Python filters out NaN values. Then, filtered\_list is converted back to a list for [further processing](https://pythonguides.com/machine-learning-image-processing/). ### 4\. Use the isnan() math Module in Python To remove NaN values from the Python list, we can use the isnan() function, which is an inbuilt method of the math module in Python. It will check all the elements and return True, where it will find NaN. ``` from math import isnan original_list = [1, 2, float('nan'), 4, float('nan'), 6] cleaned_list = [] for i in original_list: if not isnan(i): cleaned_list+=[i] print(cleaned_list) ``` I’ve initialized the original\_list [list in Python](https://pythonguides.com/create-a-list-in-python/) with numerical values, including NaN values that float(‘nan’) represents. Then, iterate through each element i in original\_list. The isnan() function in Python is used to check if i is not a NaN value. **Output** ``` [1, 2, 4, 6] ``` You can refer to the screenhsot below to see the output. ![isnan method to Remove NaN Values from a List in Python](https://pythonguides.com/wp-content/uploads/2024/01/isnan-method-to-remove-nan-from-a-list-in-python.jpg) This method uses Python’s math.isnan() for a clear and reliable way to detect and remove NaN values from a list. ### 5: Remove NaN from the Numpy array To remove NaN values from a list from [Python NumPy array](https://pythonguides.com/python-numpy-empty-array/), we will use the isnan() method of the numpy library to check whether the element is NaN or not, and it will return True or False based on whether the element is NaN. If an element is NaN in the array, it will return True. **Code** ``` import numpy as np from numpy import nan data = np.array([5, 12, nan, 7,nan,9]) filtered_data = data[np.logical_not(np.isnan(data))] print(filtered_data) ``` We used NumPy’s isnan() function in Python to identify NaN values within the array data. The np.logical\_not() function is used to negate this result. **Output** ``` [ 5. 12. 7. 9.] ``` You can refer to the screenshot below to see the output. ![How to remove NaN values from Numpy array](https://pythonguides.com/wp-content/uploads/2024/01/How-to-remove-NaN-values-from-Numpy-array.jpg) This method efficiently removes NaN values from a NumPy array using np.isnan() with np.logical\_not() for clean, numeric-only data. ### 6\. Remove NaN from the List in Pandas To remove NaN from a list using Pandas, there is one [inbuilt function in Python](https://pythonguides.com/built-in-functions-in-python/) called dropna(), which will directly remove the NaN values from the series in Python, and then you can convert it to a list using the tolist() method. Here is an instance to remove NaN values from a list in Python using the pandas library: Code ``` import pandas as pd original_list = [1, 2, float('nan'), 4, float('nan'), 6] series = pd.Series(original_list) cleaned_list = series.dropna().tolist() print(cleaned_list) ``` We’ve used the dropna() function in [Python Pandas to remove](https://pythonguides.com/remove-all-non-numeric-characters-in-pandas/) any NaN values from the series of original lists, resulting in a cleaned\_list. Finally, the tolist() function in Python converts the cleaned series into a list format. **Output** ``` [1.0, 2.0, 4.0, 6.0] ``` You can refer to the screenshot below to see the output. ![How to remove NaN from the list using pandas in python](https://pythonguides.com/wp-content/uploads/2024/01/How-to-remove-NaN-from-the-list-using-pandas-in-python.jpg) This method removes [NaN values](https://pythonguides.com/pandas-replace-nan-with-0/) from a list using Pandas’ dropna() and converts the cleaned series back into a list with tolist(). Here, I’ve covered all the different ways to remove the NaN value from the list in Python using for loop, list comprehension, filter method, isnan() method from math module, isnan() method from numpy, and dropna() method from Pandas. Each method offers its advantages and can be chosen based on specific requirements. You may like to read other Python tutorials: - [Find the Mean of a List in Python](https://pythonguides.com/how-to-find-mean-of-a-list-python/) - [Sum a List in Python Without the Sum Function](https://pythonguides.com/sum-all-the-items-in-python-list-without-using-sum/) - [Python Sort List Alphabetically](https://pythonguides.com/sort-a-list-alphabetically-in-python/) - [Sum Elements in a List in Python](https://pythonguides.com/sum-elements-in-list-in-python-using-for-loop/) ![Bijay - Python Expert](https://pythonguides.com/wp-content/uploads/2023/09/Bijay_Microsoft_MVP-.png) [Bijay Kumar](https://pythonguides.com/author/fewlines4biju/) I am Bijay Kumar, a [Microsoft MVP](https://mvp.microsoft.com/en-us/PublicProfile/5000972) in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. [Check out my profile](https://pythonguides.com/about-us/). [enjoysharepoint.com/](https://enjoysharepoint.com/) [Swap Three Variables in Python Without Using a Temporary Variable](https://pythonguides.com/swap-three-variables-without-using-temporary-variables-in-python/) [Get the First Digit of a Number in Python](https://pythonguides.com/get-the-first-digit-of-a-number-in-python/) ## Follow us in Twitter & Facebook [Follow @PythonGuides](https://twitter.com/pythonguides) [![Subscribe to PythonGuides YouTube Channel](https://pythonguides.com/wp-content/uploads/2025/05/Subscribe-to-PythonGuides-YouTube-Channel.png)](https://www.youtube.com/@pythonguides?sub_confirmation=1) ## Recent Posts - [Ways to Replace Values in a Pandas Column](https://pythonguides.com/pandas-replace-values-in-column/) - [Ways to Convert Pandas Series to DataFrame in Python](https://pythonguides.com/pandas-series-to-dataframe-python/) - [How to Count Unique Values in a Pandas Column](https://pythonguides.com/pandas-count-unique-values-column/) - [How to Concatenate Two DataFrames in Pandas](https://pythonguides.com/pandas-concat-two-dataframes/) - [How to Delete Columns in a Pandas DataFrame](https://pythonguides.com/delete-columns-pandas-dataframe/) - [About Us](https://pythonguides.com/about-us/) - [Contact](https://pythonguides.com/contact/) - [Privacy Policy](https://pythonguides.com/privacy-policy/) - [Sitemap](https://pythonguides.com/sitemap/) © 2026 PythonGuides.com ![51 Python Programs](https://pythonguides.com/wp-content/uploads/2025/01/Top-51-Python-Programs.png) ## 51 PYTHON PROGRAMS PDF FREE Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs. ![pyython developer roadmap](https://pythonguides.com/wp-content/uploads/2025/01/pyython-developer-roadmap.png) ## Aspiring to be a Python developer? Download a FREE PDF on how to become a Python developer. ## Let’s be friends Be the first to know about sales and special discounts.
Readable Markdown
While cleaning a dataset for a project, I ran into an issue where my Python list had a mix of numbers and `NaN` values. If you’ve worked with real-world data in the US, say, sales reports, healthcare data, or survey results, you know how common missing values can be. The problem is simple: NaN (Not a Number) values can break calculations and give unexpected results. Unfortunately, Python lists don’t have a built-in method to directly [filter them out](https://pythonguides.com/filter-not-in-django/). I’ve tried different approaches, and in this tutorial, I’ll show you the most effective methods I use to **remove NaN values from a list in Python**. Table of Contents - [Methods to Remove NaN Values from a List in Python](https://pythonguides.com/remove-nan-values-from-a-list-in-python/#Methods_to_Remove_NaN_Values_from_a_List_in_Python) - [1: Use the For Loop in Python](https://pythonguides.com/remove-nan-values-from-a-list-in-python/#1_Use_the_For_Loop_in_Python) - [2: Use List Comprehension in Python](https://pythonguides.com/remove-nan-values-from-a-list-in-python/#2_Use_List_Comprehension_in_Python) - [3: Use the Filter Method in Python](https://pythonguides.com/remove-nan-values-from-a-list-in-python/#3_Use_the_Filter_Method_in_Python) - [4\. Use the isnan() math Module in Python](https://pythonguides.com/remove-nan-values-from-a-list-in-python/#4_Use_the_isnan_math_Module_in_Python) - [5: Remove NaN from the Numpy array](https://pythonguides.com/remove-nan-values-from-a-list-in-python/#5_Remove_NaN_from_the_Numpy_array) - [6\. Remove NaN from the List in Pandas](https://pythonguides.com/remove-nan-values-from-a-list-in-python/#6_Remove_NaN_from_the_List_in_Pandas) Let me show you the methods to remove NaN values from a list in Python. ### 1: Use the For Loop in Python The [for loop in Python](https://pythonguides.com/for-loop-vs-while-loop-in-python/) is a common and effective way to remove NaN values from a list. ``` original_data = [1, 2, 3, 4, float('nan'), 6] cleaned_data = [] for x in original_data: if x == x: cleaned_data.append(x) print(cleaned_data) ``` In this code, we [iterate through each element](https://pythonguides.com/iterate-through-a-string-in-python/) in the original\_data list in Python. The condition if x == x checks if the element is not NaN (since NaN does not equal itself) If the condition is true, we append the element to the cleaned\_data list in Python. ``` # When it iterates to NaN == NaN, then it will return False if x == x: cleaned_data.append(x) ``` **Output** ``` [1, 2, 3, 4, 6] ``` You can refer to the screenshot below to see the output. ![How to remove nan from a list in python](https://pythonguides.com/wp-content/uploads/2024/01/How-to-remove-nan-from-a-list-in-python-1024x388.jpg) This method removes NaN values from a list by using a for loop and the condition x == x, which filters out NaN since it is [not equal to itself](https://pythonguides.com/check-array-equality-in-typescript/). ### 2: Use List Comprehension in Python List comprehension is a concise and elegant way to create lists in Python. It offers a more compact syntax compared to loops. In the context of removing NaN values from a list. ``` employee_age = [42, 35, float('nan'), 26, float('nan'), 28] filtered_list = [x for x in employee_age if x == x] print(filtered_list) ``` We use the same logic we used in the previous example, using list comprehension in Python with fewer lines of code and a faster approach. **Output** ``` [42, 35, 26, 28] ``` You can refer to the screenshot below to see the output. ![remove NaN value in python](https://pythonguides.com/wp-content/uploads/2024/01/remove-NaN-value-in-python.jpg) This method removes NaN values efficiently using [list comprehension](https://pythonguides.com/python-list-comprehension-using-if-else/), providing a shorter and faster alternative to a traditional loop. ### 3: Use the Filter Method in Python The filter() method is a built-in function of Python that applies a specified function to each item of the collection and returns an iterator containing only the items for which the function evaluates to True. **Code** ``` week_sales = [5000, 8000, float('nan'), 2000, float('nan'), 3000, 9000] filtered_list = list(filter(lambda x: x == x, week_sales )) print(filtered_list) ``` The filter() method in Python removes NaN values from the week\_sales list by applying a lambda function that checks each element for equality with itself. **Output** ``` [5000, 8000, 2000, 3000, 9000] ``` You can refer to the screenshot below to see the output. ![drop nan values from the list in python](https://pythonguides.com/wp-content/uploads/2024/01/drop-nan-values-from-the-list-in-python.jpg) Since NaN does not equal itself, the lambda function in Python filters out NaN values. Then, filtered\_list is converted back to a list for [further processing](https://pythonguides.com/machine-learning-image-processing/). ### 4\. Use the isnan() math Module in Python To remove NaN values from the Python list, we can use the isnan() function, which is an inbuilt method of the math module in Python. It will check all the elements and return True, where it will find NaN. ``` from math import isnan original_list = [1, 2, float('nan'), 4, float('nan'), 6] cleaned_list = [] for i in original_list: if not isnan(i): cleaned_list+=[i] print(cleaned_list) ``` I’ve initialized the original\_list [list in Python](https://pythonguides.com/create-a-list-in-python/) with numerical values, including NaN values that float(‘nan’) represents. Then, iterate through each element i in original\_list. The isnan() function in Python is used to check if i is not a NaN value. **Output** ``` [1, 2, 4, 6] ``` You can refer to the screenhsot below to see the output. ![isnan method to Remove NaN Values from a List in Python](https://pythonguides.com/wp-content/uploads/2024/01/isnan-method-to-remove-nan-from-a-list-in-python.jpg) This method uses Python’s math.isnan() for a clear and reliable way to detect and remove NaN values from a list. ### 5: Remove NaN from the Numpy array To remove NaN values from a list from [Python NumPy array](https://pythonguides.com/python-numpy-empty-array/), we will use the isnan() method of the numpy library to check whether the element is NaN or not, and it will return True or False based on whether the element is NaN. If an element is NaN in the array, it will return True. **Code** ``` import numpy as np from numpy import nan data = np.array([5, 12, nan, 7,nan,9]) filtered_data = data[np.logical_not(np.isnan(data))] print(filtered_data) ``` We used NumPy’s isnan() function in Python to identify NaN values within the array data. The np.logical\_not() function is used to negate this result. **Output** ``` [ 5. 12. 7. 9.] ``` You can refer to the screenshot below to see the output. ![How to remove NaN values from Numpy array](https://pythonguides.com/wp-content/uploads/2024/01/How-to-remove-NaN-values-from-Numpy-array.jpg) This method efficiently removes NaN values from a NumPy array using np.isnan() with np.logical\_not() for clean, numeric-only data. ### 6\. Remove NaN from the List in Pandas To remove NaN from a list using Pandas, there is one [inbuilt function in Python](https://pythonguides.com/built-in-functions-in-python/) called dropna(), which will directly remove the NaN values from the series in Python, and then you can convert it to a list using the tolist() method. Here is an instance to remove NaN values from a list in Python using the pandas library: Code ``` import pandas as pd original_list = [1, 2, float('nan'), 4, float('nan'), 6] series = pd.Series(original_list) cleaned_list = series.dropna().tolist() print(cleaned_list) ``` We’ve used the dropna() function in [Python Pandas to remove](https://pythonguides.com/remove-all-non-numeric-characters-in-pandas/) any NaN values from the series of original lists, resulting in a cleaned\_list. Finally, the tolist() function in Python converts the cleaned series into a list format. **Output** ``` [1.0, 2.0, 4.0, 6.0] ``` You can refer to the screenshot below to see the output. ![How to remove NaN from the list using pandas in python](https://pythonguides.com/wp-content/uploads/2024/01/How-to-remove-NaN-from-the-list-using-pandas-in-python.jpg) This method removes [NaN values](https://pythonguides.com/pandas-replace-nan-with-0/) from a list using Pandas’ dropna() and converts the cleaned series back into a list with tolist(). Here, I’ve covered all the different ways to remove the NaN value from the list in Python using for loop, list comprehension, filter method, isnan() method from math module, isnan() method from numpy, and dropna() method from Pandas. Each method offers its advantages and can be chosen based on specific requirements. You may like to read other Python tutorials: - [Find the Mean of a List in Python](https://pythonguides.com/how-to-find-mean-of-a-list-python/) - [Sum a List in Python Without the Sum Function](https://pythonguides.com/sum-all-the-items-in-python-list-without-using-sum/) - [Python Sort List Alphabetically](https://pythonguides.com/sort-a-list-alphabetically-in-python/) - [Sum Elements in a List in Python](https://pythonguides.com/sum-elements-in-list-in-python-using-for-loop/) ![Bijay - Python Expert](https://pythonguides.com/wp-content/uploads/2023/09/Bijay_Microsoft_MVP-.png) I am Bijay Kumar, a [Microsoft MVP](https://mvp.microsoft.com/en-us/PublicProfile/5000972) in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. [Check out my profile](https://pythonguides.com/about-us/).
Shard35 (laksa)
Root Hash11707473592055126435
Unparsed URLcom,pythonguides!/remove-nan-values-from-a-list-in-python/ s443