âčïž Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0.2 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://codegym.cc/groups/posts/remove-nan-using-python |
| Last Crawled | 2026-04-12 06:23:17 (5 days ago) |
| First Indexed | 2024-08-16 09:09:29 (1 year ago) |
| HTTP Status Code | 200 |
| Meta Title | Remove NaN Using Python |
| Meta Description | Welcome, fellow, today, weâre diving into a topic thatâs not only essential for data processing but also pretty common when youâre working with real-world datasets. Weâre talking about those pesky NaNsâshort for "Not a Number" |
| Meta Canonical | null |
| Boilerpipe Text | Welcome, fellow, today, weâre diving into a topic thatâs not only essential for data processing but also pretty common when youâre working with real-world datasets. Weâre talking about those pesky NaNsâshort for "Not a Number"âthat tend to pop up in your data and mess with your calculations. But fear not! By the end of this article, youâll be equipped with multiple techniques to gracefully handle and remove NaNs from both lists and arrays in Python. Ready? Letâs jump in!
Introduction
So, youâve got a dataset, and youâre ready to work your Python magic on it. But waitâwhatâs this? Some of your data points arenât numbers! Instead, theyâre NaN (Not a Number). These NaNs can sneak into your dataset for various reasons, such as missing values or errors during data collection. Unfortunately, NaNs can throw off your calculations and analyses, leading to inaccurate results. But donât worryâyouâre catching on to everything so quickly! In this article, weâll explore several methods to remove NaNs from lists and arrays in Python.
Methods of Removing NaN from a List
Letâs start with lists. Lists in Python are incredibly versatile, and removing NaN values from them can be done in a few different ways. Here are the most common methods:
1. Using List Comprehension
List comprehension is a concise way to create lists in Python, and itâs perfect for filtering out NaN values. Hereâs how you can use it:
import math
data = [1, 2, float('nan'), 4, 5, float('nan'), 7]
# Remove NaN values using list comprehension
clean_data = [x for x in data if not math.isnan(x)]
print(clean_data)
Explanation
:
We first import the
math
module to use the
math.isnan()
function, which checks if a value is NaN.
The list comprehension
[x for x in data if not math.isnan(x)]
creates a new list containing only the elements from
data
that are not NaN.
Output
:
[1, 2, 4, 5, 7]
Excellent! As you can see, the NaN values are filtered out, and youâre left with a clean list.
2. Using the
filter()
Function
Another approach is to use the
filter()
function, which is a built-in Python function that constructs an iterator from elements of an iterable for which a function returns true.
import math
data = [1, 2, float('nan'), 4, 5, float('nan'), 7]
# Remove NaN values using filter() and math.isnan
clean_data = list(filter(lambda x: not math.isnan(x), data))
print(clean_data)
Explanation
:
filter()
applies the lambda function
lambda x: not math.isnan(x)
to each element in
data
, and returns an iterator with only the elements for which the function returns
True
.
We then convert this iterator back into a list.
Output
:
[1, 2, 4, 5, 7]
Smooth and straightforward, right?
3. Using the
pandas
Library
If youâre working with data, chances are youâre already using the
pandas
library. It provides a simple and efficient way to handle NaNs in lists.
import pandas as pd
data = [1, 2, float('nan'), 4, 5, float('nan'), 7]
# Convert list to a pandas Series
data_series = pd.Series(data)
# Remove NaN values using dropna()
clean_data = data_series.dropna().tolist()
print(clean_data)
Explanation
:
We first convert the list to a
pandas
Series, which is a one-dimensional array-like object.
The
dropna()
function removes all NaN values from the Series.
Finally, we convert the Series back to a list.
Output
:
[1, 2, 4, 5, 7]
Using
pandas
is especially helpful if youâre already using it for other data manipulations.
Methods of Removing NaN from an Array
Now letâs tackle arrays. Arrays are slightly different from lists, and you might encounter them if youâre working with the
numpy
library. Hereâs how you can handle NaNs in arrays.
1. Using
numpy.isnan()
and Boolean Indexing
numpy
provides a very intuitive way to remove NaNs from arrays using
numpy.isnan()
combined with Boolean indexing.
import numpy as np
data = np.array([1, 2, np.nan, 4, 5, np.nan, 7])
# Remove NaN values using Boolean indexing
clean_data = data[~np.isnan(data)]
print(clean_data)
Explanation
:
np.isnan(data)
returns a Boolean array where
True
corresponds to NaN values.
The tilde
~
operator negates the Boolean array, so weâre left with
True
for non-NaN values.
We then use this Boolean array to index the original array, effectively filtering out the NaNs.
Output
:
[1. 2. 4. 5. 7.]
Neat, right? This method is both powerful and concise.
2. Using
numpy.compress()
The
numpy.compress()
function is another way to filter out NaNs from an array, especially if you prefer a more explicit approach.
import numpy as np
data = np.array([1, 2, np.nan, 4, 5, np.nan, 7])
# Create a Boolean mask for non-NaN values
mask = ~np.isnan(data)
# Remove NaN values using numpy.compress()
clean_data = np.compress(mask, data)
print(clean_data)
Explanation
:
We first create a Boolean mask
mask
that indicates which elements are not NaN.
numpy.compress(mask, data)
then compresses the array, keeping only the elements where
mask
is
True
.
Output
:
[1. 2. 4. 5. 7.]
3. Using
pandas
with Arrays
Just like with lists, you can use
pandas
to handle NaNs in arrays as well.
import numpy as np
import pandas as pd
data = np.array([1, 2, np.nan, 4, 5, np.nan, 7])
# Convert numpy array to pandas Series
data_series = pd.Series(data)
# Remove NaN values using dropna()
clean_data = data_series.dropna().to_numpy()
print(clean_data)
Explanation
:
We convert the
numpy
array to a
pandas
Series.
Use
dropna()
to remove the NaN values.
Convert the cleaned Series back to a
numpy
array.
Output
:
[1. 2. 4. 5. 7.]
Pandas is versatile, and this method works well if youâre switching between lists and arrays.
Summary and Conclusion
Congratulations! Youâve just learned several methods to remove NaN values from both lists and arrays in Python. Whether youâre using list comprehension,
filter()
, or
pandas
for lists, or
numpy
for arrays, youâve got the tools to keep your data clean and your calculations accurate.
In summary:
For lists
: You can use list comprehension,
filter()
, or the
pandas
library.
For arrays
:
numpy.isnan()
with Boolean indexing,
numpy.compress()
, or
pandas
can be your go-to methods.
Remember, the method you choose depends on your specific needs and the libraries youâre already using in your project. Keep practicing, and soon enough, handling NaNs will become second nature to you. You're doing great, and this is just one more step on your Python journey!
Additional Resources
If you want to dive deeper into handling NaNs and other data processing tasks, here are some resources you might find helpful:
Pandas Documentation
NumPy Documentation
Pythonâs Math Module |
| Markdown | [Promotion](https://codegym.cc/sale)
[CodeGym University](https://codegym.cc/s/university_link_menu_en)
Learning
[Courses](https://codegym.cc/courses)
[Tasks](https://codegym.cc/tasks)
[Surveys & Quizzes](https://codegym.cc/quizzes)
[Games](https://codegym.cc/projects/games)
[Help](https://codegym.cc/help)
[Schedule](https://codegym.cc/schedule)
Community
[Users](https://codegym.cc/users)
[Forum](https://codegym.cc/forum)
[Chat](https://codegym.cc/chat)
[Articles](https://codegym.cc/groups/posts)
[Success stories](https://codegym.cc/groups/stories)
[Activity](https://codegym.cc/news)
[Reviews](https://codegym.cc/about/reviews)
[Subscriptions](https://codegym.cc/prices)
Light theme
Article
- [Reviews](https://codegym.cc/about/reviews)
- [About us](https://codegym.cc/about-us)
[Start Start learning](https://codegym.cc/welcome)
- [Articles](https://codegym.cc/groups/posts)
- [Authors](https://codegym.cc/authors)
- [All groups](https://codegym.cc/groups/all)
- [All Articles List](https://codegym.cc/all-articles)
[CodeGym](https://codegym.cc/) /[Java Blog](https://codegym.cc/groups/posts) /[Learning Python](https://codegym.cc/groups/learning-python) /Remove NaN Using Python
[Author Artem Divertitto](https://codegym.cc/authors/artem-divertitto)
Senior Android Developer at **United Tech**
- 14 August 2024
- 513 views
- [0 comments](https://codegym.cc/groups/posts/remove-nan-using-python#discussion)
# Remove NaN Using Python
[Published in the Learning Python group](https://codegym.cc/groups/learning-python)
Join
Welcome, fellow, today, weâre diving into a topic thatâs not only essential for data processing but also pretty common when youâre working with real-world datasets. Weâre talking about those pesky NaNsâshort for "Not a Number"âthat tend to pop up in your data and mess with your calculations. But fear not! By the end of this article, youâll be equipped with multiple techniques to gracefully handle and remove NaNs from both lists and arrays in Python. Ready? Letâs jump in\!
## Introduction
So, youâve got a dataset, and youâre ready to work your Python magic on it. But waitâwhatâs this? Some of your data points arenât numbers! Instead, theyâre NaN (Not a Number). These NaNs can sneak into your dataset for various reasons, such as missing values or errors during data collection. Unfortunately, NaNs can throw off your calculations and analyses, leading to inaccurate results. But donât worryâyouâre catching on to everything so quickly! In this article, weâll explore several methods to remove NaNs from lists and arrays in Python.
## Methods of Removing NaN from a List
Letâs start with lists. Lists in Python are incredibly versatile, and removing NaN values from them can be done in a few different ways. Here are the most common methods:
### 1\. Using List Comprehension
List comprehension is a concise way to create lists in Python, and itâs perfect for filtering out NaN values. Hereâs how you can use it:
[![Kotlin]()](https://codegym.cc/s/dynamic_banners_kotlin_en)
```
import math
data = [1, 2, float('nan'), 4, 5, float('nan'), 7]
# Remove NaN values using list comprehension
clean_data = [x for x in data if not math.isnan(x)]
print(clean_data)
```
Explanation:
- We first import the `math` module to use the `math.isnan()` function, which checks if a value is NaN.
- The list comprehension `[x for x in data if not math.isnan(x)]` creates a new list containing only the elements from `data` that are not NaN.
Output:
```
[1, 2, 4, 5, 7]
```
Excellent! As you can see, the NaN values are filtered out, and youâre left with a clean list.
### 2\. Using the `filter()` Function
Another approach is to use the `filter()` function, which is a built-in Python function that constructs an iterator from elements of an iterable for which a function returns true.
```
import math
data = [1, 2, float('nan'), 4, 5, float('nan'), 7]
# Remove NaN values using filter() and math.isnan
clean_data = list(filter(lambda x: not math.isnan(x), data))
print(clean_data)
```
Explanation:
- `filter()` applies the lambda function `lambda x: not math.isnan(x)` to each element in `data`, and returns an iterator with only the elements for which the function returns `True`.
- We then convert this iterator back into a list.
Output:
```
[1, 2, 4, 5, 7]
```
Smooth and straightforward, right?
### 3\. Using the `pandas` Library
If youâre working with data, chances are youâre already using the `pandas` library. It provides a simple and efficient way to handle NaNs in lists.
```
import pandas as pd
data = [1, 2, float('nan'), 4, 5, float('nan'), 7]
# Convert list to a pandas Series
data_series = pd.Series(data)
# Remove NaN values using dropna()
clean_data = data_series.dropna().tolist()
print(clean_data)
```
Explanation:
- We first convert the list to a `pandas` Series, which is a one-dimensional array-like object.
- The `dropna()` function removes all NaN values from the Series.
- Finally, we convert the Series back to a list.
Output:
```
[1, 2, 4, 5, 7]
```
Using `pandas` is especially helpful if youâre already using it for other data manipulations.
## Methods of Removing NaN from an Array
Now letâs tackle arrays. Arrays are slightly different from lists, and you might encounter them if youâre working with the `numpy` library. Hereâs how you can handle NaNs in arrays.
### 1\. Using `numpy.isnan()` and Boolean Indexing
`numpy` provides a very intuitive way to remove NaNs from arrays using `numpy.isnan()` combined with Boolean indexing.
```
import numpy as np
data = np.array([1, 2, np.nan, 4, 5, np.nan, 7])
# Remove NaN values using Boolean indexing
clean_data = data[~np.isnan(data)]
print(clean_data)
```
Explanation:
- `np.isnan(data)` returns a Boolean array where `True` corresponds to NaN values.
- The tilde `~` operator negates the Boolean array, so weâre left with `True` for non-NaN values.
- We then use this Boolean array to index the original array, effectively filtering out the NaNs.
Output:
```
[1. 2. 4. 5. 7.]
```
Neat, right? This method is both powerful and concise.
### 2\. Using `numpy.compress()`
The `numpy.compress()` function is another way to filter out NaNs from an array, especially if you prefer a more explicit approach.
```
import numpy as np
data = np.array([1, 2, np.nan, 4, 5, np.nan, 7])
# Create a Boolean mask for non-NaN values
mask = ~np.isnan(data)
# Remove NaN values using numpy.compress()
clean_data = np.compress(mask, data)
print(clean_data)
```
Explanation:
- We first create a Boolean mask `mask` that indicates which elements are not NaN.
- `numpy.compress(mask, data)` then compresses the array, keeping only the elements where `mask` is `True`.
Output:
```
[1. 2. 4. 5. 7.]
```
### 3\. Using `pandas` with Arrays
Just like with lists, you can use `pandas` to handle NaNs in arrays as well.
```
import numpy as np
import pandas as pd
data = np.array([1, 2, np.nan, 4, 5, np.nan, 7])
# Convert numpy array to pandas Series
data_series = pd.Series(data)
# Remove NaN values using dropna()
clean_data = data_series.dropna().to_numpy()
print(clean_data)
```
Explanation:
[![ALL IN ONE]()](https://codegym.cc/s/dynamic_banners_all_in_one_sale_en)
- We convert the `numpy` array to a `pandas` Series.
- Use `dropna()` to remove the NaN values.
- Convert the cleaned Series back to a `numpy` array.
Output:
```
[1. 2. 4. 5. 7.]
```
Pandas is versatile, and this method works well if youâre switching between lists and arrays.
## Summary and Conclusion
Congratulations! Youâve just learned several methods to remove NaN values from both lists and arrays in Python. Whether youâre using list comprehension, `filter()`, or `pandas` for lists, or `numpy` for arrays, youâve got the tools to keep your data clean and your calculations accurate.
In summary:
- For lists: You can use list comprehension, `filter()`, or the `pandas` library.
- For arrays: `numpy.isnan()` with Boolean indexing, `numpy.compress()`, or `pandas` can be your go-to methods.
Remember, the method you choose depends on your specific needs and the libraries youâre already using in your project. Keep practicing, and soon enough, handling NaNs will become second nature to you. You're doing great, and this is just one more step on your Python journey\!
## Additional Resources
If you want to dive deeper into handling NaNs and other data processing tasks, here are some resources you might find helpful:
- [Pandas Documentation](https://pandas.pydata.org/pandas-docs/stable/)
- [NumPy Documentation](https://numpy.org/doc/stable/)
- [Pythonâs Math Module](https://docs.python.org/3/library/math.html)
[Artem Divertitto](https://codegym.cc/authors/artem-divertitto)
Senior Android Developer at United Tech
Artem is a programmer-switcher. His first profession was rehabilitation specialist. Previously, he helped people restore their hea ... [\[Read full bio\]](https://codegym.cc/authors/artem-divertitto)
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
[GO TO FULL VERSION](https://codegym.cc/groups/posts/remove-nan-using-python?post=full#discussion)
Learn
- [Registration](https://codegym.cc/login/signup)
- [Java Course](https://codegym.cc/quests)
- [Help with Tasks](https://codegym.cc/help)
- [Pricing](https://codegym.cc/prices)
- [Game Projects](https://codegym.cc/projects/games)
- [Java Syntax](https://codegym.cc/groups/posts/java-syntax)
Community
- [Users](https://codegym.cc/users)
- [Articles](https://codegym.cc/groups/posts)
- [Forum](https://codegym.cc/forum)
- [Chat](https://codegym.cc/chat)
- [Success Stories](https://codegym.cc/groups/stories)
- [Activity](https://codegym.cc/news)
- [Affiliate Program](https://codegym.cc/affiliate)
Company
- [About us](https://codegym.cc/about-us)
- [Contacts](https://codegym.cc/about/contacts)
- [Reviews](https://codegym.cc/about/reviews)
- [Press Room](https://codegym.cc/press)
- [CodeGym for EDU](https://codegym.cc/edu)
- [FAQ](https://codegym.cc/about/faq)
- [Support](https://codegym.cc/login?redirectUrl=/dialogues/administration)
 CodeGym is an online course for learning Java programming from scratch. This course is a perfect way to master Java for beginners. It contains 1200+ tasks with instant verification and an essential scope of Java fundamentals theory. To help you succeed in education, weâve implemented a set of motivational features: quizzes, coding projects, content about efficient learning, and a Java developerâs career.
Follow us
Interface language
English
English
[Deutsch](https://codegym.cc/de/groups/posts) [Español](https://codegym.cc/es/groups/posts) [à€čà€żà€šà„à€Šà„](https://codegym.cc/hi/groups/posts) [Français](https://codegym.cc/fr/groups/posts) [PortuguĂȘs](https://codegym.cc/pt/groups/posts) [Polski](https://codegym.cc/pl/groups/posts) [àŠŹàŠŸàŠàŠČàŠŸ](https://codegym.cc/bn/groups/posts) [çźäœäžæ](https://codegym.cc/zh/groups/posts) [à€źà€°à€Ÿà€ à„](https://codegym.cc/mr/groups/posts) [àź€àźźàźżàźŽàŻ](https://codegym.cc/ta/groups/posts) [Italiano](https://codegym.cc/it/groups/posts) [Bahasa Indonesia](https://codegym.cc/id/groups/posts) [çčé«äžæ](https://codegym.cc/tw/groups/posts) [Nederlands](https://codegym.cc/nl/groups/posts) [æ„æŹèȘ](https://codegym.cc/ja/groups/posts) [íê”ìŽ](https://codegym.cc/ko/groups/posts) [Bulgarian](https://codegym.cc/bg/groups/posts) [Danish](https://codegym.cc/da/groups/posts) [Hungarian](https://codegym.cc/hu/groups/posts) [Basa Jawa](https://codegym.cc/jv/groups/posts) [Malay](https://codegym.cc/ms/groups/posts) [Norwegian](https://codegym.cc/no/groups/posts) [Romanian](https://codegym.cc/ro/groups/posts) [Swedish](https://codegym.cc/sv/groups/posts) [ĐŁĐșŃаŃĐœŃŃĐșа](https://codegym.cc/ua/groups/posts) [Telugu](https://codegym.cc/te/groups/posts) [Thai](https://codegym.cc/th/groups/posts) [Filipino](https://codegym.cc/tl/groups/posts) [Turkish](https://codegym.cc/tr/groups/posts) [AzÉrbaycan](https://codegym.cc/az/groups/posts) [Đ ŃŃŃĐșĐžĐč](https://codegym.cc/ru/groups/posts) [Vietnamese](https://codegym.cc/vi/groups/posts)
"Programmers Are Made, Not Born" © 2026 CodeGym
Download App
- [![Google Play]()](https://play.google.com/store/apps/details?id=com.hitechrush.codegym)
- [![Huawei AppGallery]()](https://appgallery.huawei.com/#/app/C104521663)
- ![App Store]()
 
"Programmers Are Made, Not Born" © 2026 CodeGym |
| Readable Markdown | Welcome, fellow, today, weâre diving into a topic thatâs not only essential for data processing but also pretty common when youâre working with real-world datasets. Weâre talking about those pesky NaNsâshort for "Not a Number"âthat tend to pop up in your data and mess with your calculations. But fear not! By the end of this article, youâll be equipped with multiple techniques to gracefully handle and remove NaNs from both lists and arrays in Python. Ready? Letâs jump in\!
## Introduction
So, youâve got a dataset, and youâre ready to work your Python magic on it. But waitâwhatâs this? Some of your data points arenât numbers! Instead, theyâre NaN (Not a Number). These NaNs can sneak into your dataset for various reasons, such as missing values or errors during data collection. Unfortunately, NaNs can throw off your calculations and analyses, leading to inaccurate results. But donât worryâyouâre catching on to everything so quickly! In this article, weâll explore several methods to remove NaNs from lists and arrays in Python.
## Methods of Removing NaN from a List
Letâs start with lists. Lists in Python are incredibly versatile, and removing NaN values from them can be done in a few different ways. Here are the most common methods:
### 1\. Using List Comprehension
List comprehension is a concise way to create lists in Python, and itâs perfect for filtering out NaN values. Hereâs how you can use it:
[](https://codegym.cc/s/dynamic_banners_kotlin_en)
```
import math
data = [1, 2, float('nan'), 4, 5, float('nan'), 7]
# Remove NaN values using list comprehension
clean_data = [x for x in data if not math.isnan(x)]
print(clean_data)
```
Explanation:
- We first import the `math` module to use the `math.isnan()` function, which checks if a value is NaN.
- The list comprehension `[x for x in data if not math.isnan(x)]` creates a new list containing only the elements from `data` that are not NaN.
Output:
```
[1, 2, 4, 5, 7]
```
Excellent! As you can see, the NaN values are filtered out, and youâre left with a clean list.
### 2\. Using the `filter()` Function
Another approach is to use the `filter()` function, which is a built-in Python function that constructs an iterator from elements of an iterable for which a function returns true.
```
import math
data = [1, 2, float('nan'), 4, 5, float('nan'), 7]
# Remove NaN values using filter() and math.isnan
clean_data = list(filter(lambda x: not math.isnan(x), data))
print(clean_data)
```
Explanation:
- `filter()` applies the lambda function `lambda x: not math.isnan(x)` to each element in `data`, and returns an iterator with only the elements for which the function returns `True`.
- We then convert this iterator back into a list.
Output:
```
[1, 2, 4, 5, 7]
```
Smooth and straightforward, right?
### 3\. Using the `pandas` Library
If youâre working with data, chances are youâre already using the `pandas` library. It provides a simple and efficient way to handle NaNs in lists.
```
import pandas as pd
data = [1, 2, float('nan'), 4, 5, float('nan'), 7]
# Convert list to a pandas Series
data_series = pd.Series(data)
# Remove NaN values using dropna()
clean_data = data_series.dropna().tolist()
print(clean_data)
```
Explanation:
- We first convert the list to a `pandas` Series, which is a one-dimensional array-like object.
- The `dropna()` function removes all NaN values from the Series.
- Finally, we convert the Series back to a list.
Output:
```
[1, 2, 4, 5, 7]
```
Using `pandas` is especially helpful if youâre already using it for other data manipulations.
## Methods of Removing NaN from an Array
Now letâs tackle arrays. Arrays are slightly different from lists, and you might encounter them if youâre working with the `numpy` library. Hereâs how you can handle NaNs in arrays.
### 1\. Using `numpy.isnan()` and Boolean Indexing
`numpy` provides a very intuitive way to remove NaNs from arrays using `numpy.isnan()` combined with Boolean indexing.
```
import numpy as np
data = np.array([1, 2, np.nan, 4, 5, np.nan, 7])
# Remove NaN values using Boolean indexing
clean_data = data[~np.isnan(data)]
print(clean_data)
```
Explanation:
- `np.isnan(data)` returns a Boolean array where `True` corresponds to NaN values.
- The tilde `~` operator negates the Boolean array, so weâre left with `True` for non-NaN values.
- We then use this Boolean array to index the original array, effectively filtering out the NaNs.
Output:
```
[1. 2. 4. 5. 7.]
```
Neat, right? This method is both powerful and concise.
### 2\. Using `numpy.compress()`
The `numpy.compress()` function is another way to filter out NaNs from an array, especially if you prefer a more explicit approach.
```
import numpy as np
data = np.array([1, 2, np.nan, 4, 5, np.nan, 7])
# Create a Boolean mask for non-NaN values
mask = ~np.isnan(data)
# Remove NaN values using numpy.compress()
clean_data = np.compress(mask, data)
print(clean_data)
```
Explanation:
- We first create a Boolean mask `mask` that indicates which elements are not NaN.
- `numpy.compress(mask, data)` then compresses the array, keeping only the elements where `mask` is `True`.
Output:
```
[1. 2. 4. 5. 7.]
```
### 3\. Using `pandas` with Arrays
Just like with lists, you can use `pandas` to handle NaNs in arrays as well.
```
import numpy as np
import pandas as pd
data = np.array([1, 2, np.nan, 4, 5, np.nan, 7])
# Convert numpy array to pandas Series
data_series = pd.Series(data)
# Remove NaN values using dropna()
clean_data = data_series.dropna().to_numpy()
print(clean_data)
```
Explanation:
[](https://codegym.cc/s/dynamic_banners_all_in_one_sale_en)
- We convert the `numpy` array to a `pandas` Series.
- Use `dropna()` to remove the NaN values.
- Convert the cleaned Series back to a `numpy` array.
Output:
```
[1. 2. 4. 5. 7.]
```
Pandas is versatile, and this method works well if youâre switching between lists and arrays.
## Summary and Conclusion
Congratulations! Youâve just learned several methods to remove NaN values from both lists and arrays in Python. Whether youâre using list comprehension, `filter()`, or `pandas` for lists, or `numpy` for arrays, youâve got the tools to keep your data clean and your calculations accurate.
In summary:
- For lists: You can use list comprehension, `filter()`, or the `pandas` library.
- For arrays: `numpy.isnan()` with Boolean indexing, `numpy.compress()`, or `pandas` can be your go-to methods.
Remember, the method you choose depends on your specific needs and the libraries youâre already using in your project. Keep practicing, and soon enough, handling NaNs will become second nature to you. You're doing great, and this is just one more step on your Python journey\!
## Additional Resources
If you want to dive deeper into handling NaNs and other data processing tasks, here are some resources you might find helpful:
- [Pandas Documentation](https://pandas.pydata.org/pandas-docs/stable/)
- [NumPy Documentation](https://numpy.org/doc/stable/)
- [Pythonâs Math Module](https://docs.python.org/3/library/math.html) |
| Shard | 138 (laksa) |
| Root Hash | 17877044333714262338 |
| Unparsed URL | cc,codegym!/groups/posts/remove-nan-using-python s443 |