🕷️ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

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

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
4 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://pythonguides.com/remove-nan-from-array-in-python/
Last Crawled2026-04-14 23:09:27 (4 days ago)
First Indexed2024-12-30 02:43:26 (1 year ago)
HTTP Status Code200
Meta TitleHow To Remove NaN From Array In Python?
Meta DescriptionLearn how to remove NaN values from an array in Python using methods like `numpy.isnan()` or list comprehensions. Includes syntax, examples, and practical tips.
Meta Canonicalnull
Boilerpipe Text
As a Python developer during a project for one of our USA clients, I had a requirement to remove NaN from Array in Python removing NaN (Not a Number) values is necessary to ensure the accuracy of your analysis. We will go through detailed examples to learn different methods to clean your data efficiently. Table of Contents What are NaN Values in Python? Prerequisites 1. Use numpy.isnan() and Boolean Indexing Example 2. Use numpy.nan_to_num() Example 3. Remove Rows or Columns with NaN Values Example 4. Use Pandas for DataFrames Example Conclusion What are NaN Values in Python? NaN in Python stands for “Not a Number” and is used to represent missing or undefined values in a dataset. When working with large datasets, especially in fields of finance, healthcare, etc you may encounter NaN values that can disturb your calculations and analyses. For instance, consider a dataset of average temperatures in various US cities where some data points might be missing. Read How to Reverse an Array in Python? Prerequisites Before we get into the methods, make sure you have Python NumPy installed. You can install it using pip: pip install numpy Check out How to Update an Array in Python 1. Use numpy.isnan() and Boolean Indexing The most simple way to remove NaN values from a Python NumPy array is by using the numpy.isnan() function in combination with Boolean indexing. Let’s see how this works. Example Imagine you have an array representing average monthly rainfall in inches for New York City, but some months have missing data: import numpy as np rainfall = np.array([3.4, 4.2, np.nan, 2.9, 3.1, np.nan, 4.0, 3.8, 3.7, 4.1, np.nan, 3.9]) To remove the NaN values, you can use the following code: clean_rainfall = rainfall[~np.isnan(rainfall)] print(clean_rainfall) This code will output: [3.4 4.2 2.9 3.1 4. 3.8 3.7 4.1 3.9] A screenshot of the executed example code is added below, you can have a look. Here, numpy.isnan(rainfall) returns a boolean array indicating where NaN values are located and negates this array. Read How to Print Duplicate Elements in Array in Python 2. Use numpy.nan_to_num() Another approach is to replace NaN values with a specific number using the numpy.nan_to_num() function in Python. This method is useful when you prefer to add missing values rather than remove them. Example Let’s use the same rainfall data for New York City: rainfall = np.array([3.4, 4.2, np.nan, 2.9, 3.1, np.nan, 4.0, 3.8, 3.7, 4.1, np.nan, 3.9]) You can replace NaN values with zero (or any other value) as follows: clean_rainfall = np.nan_to_num(rainfall, nan=0.0) print(clean_rainfall) This code will output: [3.4 4.2 0. 2.9 3.1 0. 4. 3.8 3.7 4.1 0. 3.9] A screenshot of the executed example code is added below, you can have a look. In this example, all NaN values are replaced with 0.0. Check out How to Convert Python Dict to Array 3. Remove Rows or Columns with NaN Values In some cases, you may want to remove entire rows or columns which contain NaN values. This method is particularly useful for 2D arrays or matrices. Example Consider a 2D array representing the average monthly temperatures for various cities in the USA: temperatures = np.array([ [32.0, 35.1, np.nan], [45.2, np.nan, 47.8], [np.nan, 50.5, 52.3], [55.1, 58.0, 60.2] ]) To remove rows with any NaN values, you can use the following code: clean_temperatures = temperatures[~np.isnan(temperatures).any(axis=1)] print(clean_temperatures) This code will output: [[55.1 58. 60.2]] A screenshot of the executed example code is added below, you can have a look. Here, np.isnan(temperatures).any(axis=1) returns a boolean array indicating which rows contain NaN values, and negates it. Read Python repeat array n times 4. Use Pandas for DataFrames If you’re working with tabular data, the Pandas library provides more easy methods to handle NaN values. You can easily remove or fill NaN values in DataFrames. Example Let’s say you have a data frame representing the average monthly temperatures for various US cities: import pandas as pd data = { 'New York': [32.0, 35.1, np.nan, 45.2, np.nan, 47.8, np.nan, 50.5, 52.3, 55.1, 58.0, 60.2], 'Los Angeles': [58.4, 60.2, 62.1, np.nan, 65.3, 68.0, 70.2, np.nan, 72.4, 74.1, 75.8, 77.5], 'Chicago': [28.2, 30.1, np.nan, 35.4, 37.6, np.nan, 40.3, 42.1, 44.0, 46.2, 48.5, np.nan] } df = pd.DataFrame(data) To remove rows with any NaN values, you can use the dropna() method: clean_df = df.dropna() print(clean_df) This code will output: New York Los Angeles Chicago 9 55.1 74.1 46.2 Alternatively, to fill NaN values with a specific value, you can use the fillna() method: filled_df = df.fillna(0.0) print(filled_df) This code will output: New York Los Angeles Chicago 0 32.0 58.4 28.2 1 35.1 60.2 30.1 2 0.0 62.1 0.0 3 45.2 0.0 35.4 4 0.0 65.3 37.6 5 47.8 68.0 0.0 6 0.0 70.2 40.3 7 50.5 0.0 42.1 8 52.3 72.4 44.0 9 55.1 74.1 46.2 10 58.0 75.8 48.5 11 60.2 77.5 0.0 Check out How to Get Values from a JSON Array in Python Conclusion In this tutorial, I helped you to learn how to remove NaN from array in Python . Whether you choose to remove or replace NaN values, NumPy and Pandas offer many tools. Topics I covered, are using numpy.isnan() and Boolean Indexing, using Numpy.nan_to_num() , Removing Rows or Columns with NaN Values , Using Pandas for DataFrames . You may also like to read: NumPy Divide Array by Scalar in Python How to Create a 2D NumPy Array in Python NumPy Array to List in Python How to Check if an Array Index Exists 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-from-array-in-python/#content "Skip to content") [![Python Guides](data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzUwIiBoZWlnaHQ9Ijc1IiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0ibm9uZSIgLz48L3N2Zz4=)](https://pythonguides.com/) [![Python Guides](data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjYyIiBoZWlnaHQ9IjU2IiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0ibm9uZSIgLz48L3N2Zz4=)](https://pythonguides.com/ "Python Guides") Menu - [Learn Python](https://pythonguides.com/start-here/) - [Start Here](https://pythonguides.com/start-here/) - [Python Roadmap](https://pythonguides.com/python-roadmap/) - [Python Tutorials](https://pythonguides.com/python-programming-tutorials/) - [Python Libraries](https://pythonguides.com/best-python-libraries/) - [Machine Learning](https://pythonguides.com/machine-learning-tutorials/) - [ML Tutorials Hub](https://pythonguides.com/machine-learning-tutorials/) - [NumPy](https://pythonguides.com/numpy-tutorials/) - [Pandas](https://pythonguides.com/pandas/) - [Matplotlib](https://pythonguides.com/matplotlib-in-python/) - [Scikit-Learn](https://pythonguides.com/scikit-learn/) - [Tensorflow](https://pythonguides.com/python-tensorflow-tutorials/) - [Keras](https://pythonguides.com/keras/) - [PyTorch](https://pythonguides.com/pytorch/) - [Web Development](https://pythonguides.com/web-dev/) - [Tools & Resources](https://pythonguides.com/remove-nan-from-array-in-python/) - [Free Online Tools](https://pythonguides.com/free-online-tools/) - [FREE eBook](https://pythonguides.com/free-ebook/) - [FREE Training Course](https://pythonguides.com/python-and-machine-learning-training-course/) - [Blogs](https://pythonguides.com/blogs/) # How to Remove NaN from Array in Python? March 19, 2025 December 26, 2024 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-from-array-in-python/#elementor-action%3Aaction%3Dpopup%3Aopen%26settings%3DeyJpZCI6IjYwNTA2IiwidG9nZ2xlIjpmYWxzZX0%3D) As a Python developer during a project for one of our USA clients, I had a requirement to **remove NaN from Array in Python** removing NaN (Not a Number) values is necessary to ensure the accuracy of your analysis. We will go through detailed examples to learn different methods to clean your data efficiently. Table of Contents [Toggle](https://pythonguides.com/remove-nan-from-array-in-python/) - [What are NaN Values in Python?](https://pythonguides.com/remove-nan-from-array-in-python/#What_are_NaN_Values_in_Python) - [Prerequisites](https://pythonguides.com/remove-nan-from-array-in-python/#Prerequisites) - [1\. Use numpy.isnan() and Boolean Indexing](https://pythonguides.com/remove-nan-from-array-in-python/#1_Use_numpyisnan_and_Boolean_Indexing) - [Example](https://pythonguides.com/remove-nan-from-array-in-python/#Example) - [2\. Use numpy.nan\_to\_num()](https://pythonguides.com/remove-nan-from-array-in-python/#2_Use_numpynan_to_num) - [Example](https://pythonguides.com/remove-nan-from-array-in-python/#Example-2) - [3\. Remove Rows or Columns with NaN Values](https://pythonguides.com/remove-nan-from-array-in-python/#3_Remove_Rows_or_Columns_with_NaN_Values) - [Example](https://pythonguides.com/remove-nan-from-array-in-python/#Example-3) - [4\. Use Pandas for DataFrames](https://pythonguides.com/remove-nan-from-array-in-python/#4_Use_Pandas_for_DataFrames) - [Example](https://pythonguides.com/remove-nan-from-array-in-python/#Example-4) - [Conclusion](https://pythonguides.com/remove-nan-from-array-in-python/#Conclusion) ## What are NaN Values in Python? NaN in [Python](https://pythonguides.com/python-programming-tutorials/) stands for “Not a Number” and is used to represent missing or undefined values in a dataset. When working with large datasets, especially in fields of finance, healthcare, etc you may encounter NaN values that can disturb your calculations and analyses. For instance, consider a dataset of average temperatures in various US cities where some data points might be missing. Read [How to Reverse an Array in Python?](https://pythonguides.com/reverse-an-array-in-python/) ## Prerequisites Before we get into the methods, make sure you have [Python NumPy](https://pythonguides.com/numpy-tutorials/) installed. You can install it using pip: ``` pip install numpy ``` Check out [How to Update an Array in Python](https://pythonguides.com/python-array/) ## 1\. Use numpy.isnan() and Boolean Indexing The most simple way to remove NaN values from a Python NumPy array is by using the `numpy.isnan()` function in combination with Boolean indexing. Let’s see how this works. ### Example Imagine you have an array representing average monthly rainfall in inches for New York City, but some months have missing data: ``` import numpy as np rainfall = np.array([3.4, 4.2, np.nan, 2.9, 3.1, np.nan, 4.0, 3.8, 3.7, 4.1, np.nan, 3.9]) ``` To remove the NaN values, you can use the following code: ``` clean_rainfall = rainfall[~np.isnan(rainfall)] print(clean_rainfall) ``` This code will output: ``` [3.4 4.2 2.9 3.1 4. 3.8 3.7 4.1 3.9] ``` A screenshot of the executed example code is added below, you can have a look. ![Remove NaN from Array in Python](data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAyNCIgaGVpZ2h0PSIzNTQiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSJub25lIiAvPjwvc3ZnPg==) Here, `numpy.isnan(rainfall)` returns a boolean array indicating where NaN values are located and negates this array. Read [How to Print Duplicate Elements in Array in Python](https://pythonguides.com/python-program-to-print-the-duplicate-elements-of-an-array/) ## 2\. Use numpy.nan\_to\_num() Another approach is to replace NaN values with a specific number using the `numpy.nan_to_num()` function in Python. This method is useful when you prefer to add missing values rather than remove them. ### Example Let’s use the same rainfall data for New York City: ``` rainfall = np.array([3.4, 4.2, np.nan, 2.9, 3.1, np.nan, 4.0, 3.8, 3.7, 4.1, np.nan, 3.9]) ``` You can replace NaN values with zero (or any other value) as follows: ``` clean_rainfall = np.nan_to_num(rainfall, nan=0.0) print(clean_rainfall) ``` This code will output: ``` [3.4 4.2 0. 2.9 3.1 0. 4. 3.8 3.7 4.1 0. 3.9] ``` A screenshot of the executed example code is added below, you can have a look. ![How to Remove NaN from Array in Python](data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAyNCIgaGVpZ2h0PSIzMjgiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSJub25lIiAvPjwvc3ZnPg==) In this example, all NaN values are replaced with 0.0. Check out [How to Convert Python Dict to Array](https://pythonguides.com/python-convert-dictionary-to-an-array/) ## 3\. Remove Rows or Columns with NaN Values In some cases, you may want to remove entire rows or columns which contain NaN values. This method is particularly useful for 2D arrays or matrices. ### Example Consider a 2D array representing the average monthly temperatures for various cities in the USA: ``` temperatures = np.array([ [32.0, 35.1, np.nan], [45.2, np.nan, 47.8], [np.nan, 50.5, 52.3], [55.1, 58.0, 60.2] ]) ``` To remove rows with any NaN values, you can use the following code: ``` clean_temperatures = temperatures[~np.isnan(temperatures).any(axis=1)] print(clean_temperatures) ``` This code will output: ``` [[55.1 58. 60.2]] ``` A screenshot of the executed example code is added below, you can have a look. ![Removing Rows or Columns with NaN Values from Array in Python](data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAyNCIgaGVpZ2h0PSI1MDgiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSJub25lIiAvPjwvc3ZnPg==) Here, `np.isnan(temperatures).any(axis=1)` returns a boolean array indicating which rows contain NaN values, and negates it. Read [Python repeat array n times](https://pythonguides.com/python-numpy-repeat/) ## 4\. Use Pandas for DataFrames If you’re working with tabular data, the Pandas library provides more easy methods to handle NaN values. You can easily remove or fill NaN values in DataFrames. ### Example Let’s say you have a data frame representing the average monthly temperatures for various US cities: ``` import pandas as pd data = { 'New York': [32.0, 35.1, np.nan, 45.2, np.nan, 47.8, np.nan, 50.5, 52.3, 55.1, 58.0, 60.2], 'Los Angeles': [58.4, 60.2, 62.1, np.nan, 65.3, 68.0, 70.2, np.nan, 72.4, 74.1, 75.8, 77.5], 'Chicago': [28.2, 30.1, np.nan, 35.4, 37.6, np.nan, 40.3, 42.1, 44.0, 46.2, 48.5, np.nan] } df = pd.DataFrame(data) ``` To remove rows with any NaN values, you can use the `dropna()` method: ``` clean_df = df.dropna() print(clean_df) ``` This code will output: ``` New York Los Angeles Chicago 9 55.1 74.1 46.2 ``` Alternatively, to fill NaN values with a specific value, you can use the `fillna()` method: ``` filled_df = df.fillna(0.0) print(filled_df) ``` This code will output: ``` New York Los Angeles Chicago 0 32.0 58.4 28.2 1 35.1 60.2 30.1 2 0.0 62.1 0.0 3 45.2 0.0 35.4 4 0.0 65.3 37.6 5 47.8 68.0 0.0 6 0.0 70.2 40.3 7 50.5 0.0 42.1 8 52.3 72.4 44.0 9 55.1 74.1 46.2 10 58.0 75.8 48.5 11 60.2 77.5 0.0 ``` Check out [How to Get Values from a JSON Array in Python](https://pythonguides.com/json-data-in-python/) ## Conclusion In this tutorial, I helped you to learn **how to remove NaN from array in Python**. Whether you choose to remove or replace NaN values, NumPy and Pandas offer many tools. Topics I covered, are using `numpy.isnan()` and Boolean Indexing, using `Numpy.nan_to_num()`, `Removing Rows or Columns with NaN Values`, `Using Pandas for DataFrames`. You may also like to read: - [NumPy Divide Array by Scalar in Python](https://pythonguides.com/python-numpy-divide/) - [How to Create a 2D NumPy Array in Python](https://pythonguides.com/python-numpy-indexing/) - [NumPy Array to List in Python](https://pythonguides.com/convert-numpy-array-to-list-in-python/) - [How to Check if an Array Index Exists in Python?](https://pythonguides.com/check-if-an-array-index-exists-in-python/) . ![Bijay - Python Expert](data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiPjxyZWN0IHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9Im5vbmUiIC8+PC9zdmc+) [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/) [How to Check if an Array Contains a Value in Python?](https://pythonguides.com/check-if-an-array-contains-a-value-in-python/) [How to Check the Type of a Variable in TypeScript?](https://pythonguides.com/check-the-type-of-a-variable-in-typescript/) ## Follow us in Twitter & Facebook [Follow @PythonGuides](https://twitter.com/pythonguides) [![Subscribe to PythonGuides YouTube Channel](data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIwIiBoZWlnaHQ9Ijc1IiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0ibm9uZSIgLz48L3N2Zz4=)](https://www.youtube.com/@pythonguides?sub_confirmation=1) ## Recent Posts - [How to Use the Pandas Apply Function to Each Row](https://pythonguides.com/pandas-apply-function-to-each-row/) - [How to Drop Rows in Pandas Based on Column Values](https://pythonguides.com/pandas-drop-rows-based-on-column-value/) - [How to Create a Pandas DataFrame from a List of Dictionaries](https://pythonguides.com/pandas-dataframe-from-list-of-dictionaries/) - [How to Change Column Type in Pandas](https://pythonguides.com/pandas-change-column-type/) - [Pandas Series vs DataFrame](https://pythonguides.com/pandas-series-vs-dataframe-comparison/) - [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](data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjUwIiBoZWlnaHQ9IjM1MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiPjxyZWN0IHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9Im5vbmUiIC8+PC9zdmc+) ## 51 PYTHON PROGRAMS PDF FREE Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs. ![pyython developer roadmap](data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjUwIiBoZWlnaHQ9IjM1MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiPjxyZWN0IHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9Im5vbmUiIC8+PC9zdmc+) ## 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
As a Python developer during a project for one of our USA clients, I had a requirement to **remove NaN from Array in Python** removing NaN (Not a Number) values is necessary to ensure the accuracy of your analysis. We will go through detailed examples to learn different methods to clean your data efficiently. Table of Contents - [What are NaN Values in Python?](https://pythonguides.com/remove-nan-from-array-in-python/#What_are_NaN_Values_in_Python) - [Prerequisites](https://pythonguides.com/remove-nan-from-array-in-python/#Prerequisites) - [1\. Use numpy.isnan() and Boolean Indexing](https://pythonguides.com/remove-nan-from-array-in-python/#1_Use_numpyisnan_and_Boolean_Indexing) - [Example](https://pythonguides.com/remove-nan-from-array-in-python/#Example) - [2\. Use numpy.nan\_to\_num()](https://pythonguides.com/remove-nan-from-array-in-python/#2_Use_numpynan_to_num) - [Example](https://pythonguides.com/remove-nan-from-array-in-python/#Example-2) - [3\. Remove Rows or Columns with NaN Values](https://pythonguides.com/remove-nan-from-array-in-python/#3_Remove_Rows_or_Columns_with_NaN_Values) - [Example](https://pythonguides.com/remove-nan-from-array-in-python/#Example-3) - [4\. Use Pandas for DataFrames](https://pythonguides.com/remove-nan-from-array-in-python/#4_Use_Pandas_for_DataFrames) - [Example](https://pythonguides.com/remove-nan-from-array-in-python/#Example-4) - [Conclusion](https://pythonguides.com/remove-nan-from-array-in-python/#Conclusion) ## What are NaN Values in Python? NaN in [Python](https://pythonguides.com/python-programming-tutorials/) stands for “Not a Number” and is used to represent missing or undefined values in a dataset. When working with large datasets, especially in fields of finance, healthcare, etc you may encounter NaN values that can disturb your calculations and analyses. For instance, consider a dataset of average temperatures in various US cities where some data points might be missing. Read [How to Reverse an Array in Python?](https://pythonguides.com/reverse-an-array-in-python/) ## Prerequisites Before we get into the methods, make sure you have [Python NumPy](https://pythonguides.com/numpy-tutorials/) installed. You can install it using pip: ``` pip install numpy ``` Check out [How to Update an Array in Python](https://pythonguides.com/python-array/) ## 1\. Use numpy.isnan() and Boolean Indexing The most simple way to remove NaN values from a Python NumPy array is by using the `numpy.isnan()` function in combination with Boolean indexing. Let’s see how this works. ### Example Imagine you have an array representing average monthly rainfall in inches for New York City, but some months have missing data: ``` import numpy as np rainfall = np.array([3.4, 4.2, np.nan, 2.9, 3.1, np.nan, 4.0, 3.8, 3.7, 4.1, np.nan, 3.9]) ``` To remove the NaN values, you can use the following code: ``` clean_rainfall = rainfall[~np.isnan(rainfall)] print(clean_rainfall) ``` This code will output: ``` [3.4 4.2 2.9 3.1 4. 3.8 3.7 4.1 3.9] ``` A screenshot of the executed example code is added below, you can have a look. ![Remove NaN from Array in Python](data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAyNCIgaGVpZ2h0PSIzNTQiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSJub25lIiAvPjwvc3ZnPg==) Here, `numpy.isnan(rainfall)` returns a boolean array indicating where NaN values are located and negates this array. Read [How to Print Duplicate Elements in Array in Python](https://pythonguides.com/python-program-to-print-the-duplicate-elements-of-an-array/) ## 2\. Use numpy.nan\_to\_num() Another approach is to replace NaN values with a specific number using the `numpy.nan_to_num()` function in Python. This method is useful when you prefer to add missing values rather than remove them. ### Example Let’s use the same rainfall data for New York City: ``` rainfall = np.array([3.4, 4.2, np.nan, 2.9, 3.1, np.nan, 4.0, 3.8, 3.7, 4.1, np.nan, 3.9]) ``` You can replace NaN values with zero (or any other value) as follows: ``` clean_rainfall = np.nan_to_num(rainfall, nan=0.0) print(clean_rainfall) ``` This code will output: ``` [3.4 4.2 0. 2.9 3.1 0. 4. 3.8 3.7 4.1 0. 3.9] ``` A screenshot of the executed example code is added below, you can have a look. ![How to Remove NaN from Array in Python](data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAyNCIgaGVpZ2h0PSIzMjgiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSJub25lIiAvPjwvc3ZnPg==) In this example, all NaN values are replaced with 0.0. Check out [How to Convert Python Dict to Array](https://pythonguides.com/python-convert-dictionary-to-an-array/) ## 3\. Remove Rows or Columns with NaN Values In some cases, you may want to remove entire rows or columns which contain NaN values. This method is particularly useful for 2D arrays or matrices. ### Example Consider a 2D array representing the average monthly temperatures for various cities in the USA: ``` temperatures = np.array([ [32.0, 35.1, np.nan], [45.2, np.nan, 47.8], [np.nan, 50.5, 52.3], [55.1, 58.0, 60.2] ]) ``` To remove rows with any NaN values, you can use the following code: ``` clean_temperatures = temperatures[~np.isnan(temperatures).any(axis=1)] print(clean_temperatures) ``` This code will output: ``` [[55.1 58. 60.2]] ``` A screenshot of the executed example code is added below, you can have a look. ![Removing Rows or Columns with NaN Values from Array in Python](data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAyNCIgaGVpZ2h0PSI1MDgiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSJub25lIiAvPjwvc3ZnPg==) Here, `np.isnan(temperatures).any(axis=1)` returns a boolean array indicating which rows contain NaN values, and negates it. Read [Python repeat array n times](https://pythonguides.com/python-numpy-repeat/) ## 4\. Use Pandas for DataFrames If you’re working with tabular data, the Pandas library provides more easy methods to handle NaN values. You can easily remove or fill NaN values in DataFrames. ### Example Let’s say you have a data frame representing the average monthly temperatures for various US cities: ``` import pandas as pd data = { 'New York': [32.0, 35.1, np.nan, 45.2, np.nan, 47.8, np.nan, 50.5, 52.3, 55.1, 58.0, 60.2], 'Los Angeles': [58.4, 60.2, 62.1, np.nan, 65.3, 68.0, 70.2, np.nan, 72.4, 74.1, 75.8, 77.5], 'Chicago': [28.2, 30.1, np.nan, 35.4, 37.6, np.nan, 40.3, 42.1, 44.0, 46.2, 48.5, np.nan] } df = pd.DataFrame(data) ``` To remove rows with any NaN values, you can use the `dropna()` method: ``` clean_df = df.dropna() print(clean_df) ``` This code will output: ``` New York Los Angeles Chicago 9 55.1 74.1 46.2 ``` Alternatively, to fill NaN values with a specific value, you can use the `fillna()` method: ``` filled_df = df.fillna(0.0) print(filled_df) ``` This code will output: ``` New York Los Angeles Chicago 0 32.0 58.4 28.2 1 35.1 60.2 30.1 2 0.0 62.1 0.0 3 45.2 0.0 35.4 4 0.0 65.3 37.6 5 47.8 68.0 0.0 6 0.0 70.2 40.3 7 50.5 0.0 42.1 8 52.3 72.4 44.0 9 55.1 74.1 46.2 10 58.0 75.8 48.5 11 60.2 77.5 0.0 ``` Check out [How to Get Values from a JSON Array in Python](https://pythonguides.com/json-data-in-python/) ## Conclusion In this tutorial, I helped you to learn **how to remove NaN from array in Python**. Whether you choose to remove or replace NaN values, NumPy and Pandas offer many tools. Topics I covered, are using `numpy.isnan()` and Boolean Indexing, using `Numpy.nan_to_num()`, `Removing Rows or Columns with NaN Values`, `Using Pandas for DataFrames`. You may also like to read: - [NumPy Divide Array by Scalar in Python](https://pythonguides.com/python-numpy-divide/) - [How to Create a 2D NumPy Array in Python](https://pythonguides.com/python-numpy-indexing/) - [NumPy Array to List in Python](https://pythonguides.com/convert-numpy-array-to-list-in-python/) - [How to Check if an Array Index Exists in Python?](https://pythonguides.com/check-if-an-array-index-exists-in-python/) . ![Bijay - Python Expert](data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiPjxyZWN0IHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9Im5vbmUiIC8+PC9zdmc+) 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-from-array-in-python/ s443