âšď¸ 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 | 2.7 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://stackoverflow.com/questions/37147735/remove-nan-value-from-a-set |
| Last Crawled | 2026-01-16 04:25:13 (2 months ago) |
| First Indexed | not set |
| HTTP Status Code | 200 |
| Meta Title | python - Remove NaN value from a set - Stack Overflow |
| Meta Description | null |
| Meta Canonical | null |
| Boilerpipe Text | This question shows research effort; it is useful and clear
26
Save this question.
Show activity on this post.
Is it possible to easily remove NaN values for a Python Set object? Given that NaN values do not equal anything (and
float('nan') is float('nan')
is also
False
), you can end up with many NaN values in a Set.
>>>
a =
set
( (
float
(
'nan'
),
float
(
'nan'
),
'a'
) )
>>>
a
{nan, nan,
'a'
}
The best I can come up with it to define a function like math.isnan, but that is tolerant of non-float types like:
def
my_isnan
(
x
):
try
:
return
math.isnan(x)
except
TypeError:
return
False
Then you can use a set comprehension like this:
>>>
{x
for
x
in
a
if
not
my_isnan(x)}
{
'a'
}
asked
May 10, 2016 at 19:52
6
This answer is useful
21
Save this answer.
Show activity on this post.
In practice, you could look at the fact that
nan != nan
as a feature, not a bug:
>>>
a = {
float
(
'nan'
),
float
(
'nan'
),
'a'
}
>>>
a
{nan, nan,
'a'
}
>>>
{x
for
x
in
a
if
x==x}
{
'a'
}
On the positive side, no need for a helper function. On the negative side, if you have a non-nan object which is also not equal to itself, you'll remove that too.
answered
May 10, 2016 at 20:36
1 Comment
I knew there had to be some way with resorting to the helper function. Thanks!
2016-05-10T20:43:04.593Z+00:00
This answer is useful
8
Save this answer.
Show activity on this post.
Use
pd.notna()
from pandas, e.g.:
In [
219
]:
import
pandas
as
pd
In [
220
]: a =
set
((
float
(
'nan'
),
float
(
'nan'
),
'a'
))
In [
221
]: a = {x
for
x
in
a
if
pd.notna(x)}
In [
222
]: a
Out[
222
]: {
'a'
}
answered
Nov 16, 2018 at 23:20
Comments
This answer is useful
4
Save this answer.
Show activity on this post.
Also you can use
filter
:
In[
75
]: a =
set
((
float
(
'nan'
),
float
(
'nan'
),
'a'
))
In[
76
]:
set
(
filter
(
lambda
x: x == x , a))
Out[
76
]: {
'a'
}
answered
May 10, 2016 at 20:36
ej_f
460
3 silver badges
9 bronze badges
Comments
This answer is useful
3
Save this answer.
Show activity on this post.
We can simply use the .remove() method
In[
1
]: a =
set
([np.nan,
"A"
])
In[
2
]: a
Out: {
'A'
, nan}
In[
3
]: a.remove(np.nan)
In[
4
]: a
Out: {
'A'
}
answered
Oct 15, 2020 at 21:49
3 Comments
Please consider add some explanation/comments to the code.
2020-10-15T22:47:25.62Z+00:00
As @Fre_der_ik noted,
remove()
will raise an error if there is no NaN in the set. Use
discard()
instead.
2020-11-26T15:13:12.77Z+00:00
@BenoĂŽt Lebreton Your answer helped me a lot.
2021-02-13T07:33:12.087Z+00:00
This answer is useful
0
Save this answer.
Show activity on this post.
I cannot make a comment, so I combine the answers above, with some explanation (for beginners).
Create a set, including NaN (numpy.nan value)
In[
1
]:
import
numpy
as
np
In[
2
]: a =
set
([np.nan,
'A'
])
Check the created set as result:
In[
3
]: a
Out: {
'A'
, nan}
Discard (better then remove which could lead to KeyError if there is non NaN in the set) NaNs:
In[
4
]: a.discard(np.nan)
Check the result:
In[
5
]: a
Out: {
'A'
}
answered
Aug 2, 2023 at 8:14
Comments
Start asking to get answers
Find the answer to your question by asking.
Ask question
Explore related questions
See similar questions with these tags. |
| Markdown | # 
By clicking âSign upâ, you agree to our [terms of service](https://stackoverflow.com/legal/terms-of-service/public) and acknowledge you have read our [privacy policy](https://stackoverflow.com/legal/privacy-policy).
# OR
Already have an account? [Log in](https://stackoverflow.com/users/login)
[Skip to main content](https://stackoverflow.com/questions/37147735/remove-nan-value-from-a-set#content)
[Stack Overflow](https://stackoverflow.com/)
1. [About](https://stackoverflow.co/)
2. Products
3. [For Teams](https://stackoverflow.co/internal/)
1. [Stack Internal Implement a knowledge platform layer to power your enterprise and AI tools.](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=stack-overflow-for-teams)
2. [Stack Data Licensing Get access to top-class technical expertise with trusted & attributed content.](https://stackoverflow.co/data-licensing/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=overflow-api)
3. [Stack Ads Connect your brand to the worldâs most trusted technologist communities.](https://stackoverflow.co/advertising/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=stack-overflow-advertising)
4. [Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal.](https://stackoverflow.blog/releases/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=releases)
5. [About the company](https://stackoverflow.co/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=about-the-company) [Visit the blog](https://stackoverflow.blog/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=blog)
1. ### [current community](https://stackoverflow.com/)
- [Stack Overflow](https://stackoverflow.com/)
[help](https://stackoverflow.com/help) [chat](https://chat.stackoverflow.com/?tab=explore)
- [Meta Stack Overflow](https://meta.stackoverflow.com/)
### your communities
[Sign up](https://stackoverflow.com/users/signup?ssrc=site_switcher&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F37147735%2Fremove-nan-value-from-a-set) or [log in](https://stackoverflow.com/users/login?ssrc=site_switcher&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F37147735%2Fremove-nan-value-from-a-set) to customize your list.
### [more stack exchange communities](https://stackexchange.com/sites)
[company blog](https://stackoverflow.blog/)
2. [Log in](https://stackoverflow.com/users/login?ssrc=head&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F37147735%2Fremove-nan-value-from-a-set)
3. [Sign up](https://stackoverflow.com/users/signup?ssrc=head&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F37147735%2Fremove-nan-value-from-a-set)
# Let's set up your homepage Select a few topics you're interested in:
python
javascript
c\#
reactjs
java
android
html
flutter
c++
node.js
typescript
css
r
php
angular
next.js
spring-boot
machine-learning
sql
excel
ios
azure
docker
Or search from our full list:
- javascript
- python
- java
- c\#
- php
- android
- html
- jquery
- c++
- css
- ios
- sql
- mysql
- r
- reactjs
- node.js
- arrays
- c
- asp.net
- json
- python-3.x
- .net
- ruby-on-rails
- sql-server
- swift
- django
- angular
- objective-c
- excel
- pandas
- angularjs
- regex
- typescript
- ruby
- linux
- ajax
- iphone
- vba
- xml
- laravel
- spring
- asp.net-mvc
- database
- wordpress
- string
- flutter
- postgresql
- mongodb
- wpf
- windows
- xcode
- amazon-web-services
- bash
- git
- oracle-database
- spring-boot
- dataframe
- azure
- firebase
- list
- multithreading
- docker
- vb.net
- react-native
- eclipse
- algorithm
- powershell
- macos
- visual-studio
- numpy
- image
- forms
- scala
- function
- vue.js
- performance
- twitter-bootstrap
- selenium
- winforms
- kotlin
- loops
- dart
- express
- hibernate
- sqlite
- matlab
- python-2.7
- shell
- rest
- apache
- entity-framework
- android-studio
- csv
- maven
- linq
- qt
- dictionary
- unit-testing
- asp.net-core
- facebook
- apache-spark
- tensorflow
- file
- swing
- class
- unity-game-engine
- sorting
- date
- authentication
- go
- symfony
- t-sql
- opencv
- matplotlib
- .htaccess
- google-chrome
- for-loop
- datetime
- codeigniter
- perl
- http
- validation
- sockets
- google-maps
- object
- uitableview
- xaml
- oop
- visual-studio-code
- if-statement
- cordova
- ubuntu
- web-services
- email
- android-layout
- github
- spring-mvc
- elasticsearch
- kubernetes
- selenium-webdriver
- ms-access
- ggplot2
- user-interface
- parsing
- pointers
- google-sheets
- c++11
- security
- machine-learning
- google-apps-script
- ruby-on-rails-3
- templates
- flask
- nginx
- variables
- exception
- sql-server-2008
- gradle
- debugging
- tkinter
- delphi
- listview
- jpa
- asynchronous
- haskell
- web-scraping
- pdf
- jsp
- ssl
- amazon-s3
- google-cloud-platform
- testing
- jenkins
- xamarin
- wcf
- batch-file
- generics
- npm
- ionic-framework
- network-programming
- unix
- recursion
- google-app-engine
- mongoose
- visual-studio-2010
- .net-core
- android-fragments
- assembly
- animation
- math
- svg
- rust
- session
- intellij-idea
- hadoop
- join
- curl
- winapi
- django-models
- laravel-5
- next.js
- url
- heroku
- http-redirect
- tomcat
- google-cloud-firestore
- inheritance
- webpack
- gcc
- image-processing
- swiftui
- keras
- asp.net-mvc-4
- logging
- dom
- matrix
- pyspark
- actionscript-3
- button
- post
- optimization
- firebase-realtime-database
- jquery-ui
- cocoa
- xpath
- iis
- web
- d3.js
- javafx
- firefox
- xslt
- internet-explorer
- caching
- select
- asp.net-mvc-3
- opengl
- events
- asp.net-web-api
- plot
- dplyr
- encryption
- magento
- stored-procedures
- search
- amazon-ec2
- ruby-on-rails-4
- memory
- canvas
- multidimensional-array
- audio
- random
- jsf
- vector
- redux
- cookies
- input
- facebook-graph-api
- flash
- indexing
- xamarin.forms
- arraylist
- ipad
- cocoa-touch
- data-structures
- video
- model-view-controller
- azure-devops
- serialization
- apache-kafka
- jdbc
- razor
- woocommerce
- awk
- routes
- mod-rewrite
- servlets
- excel-formula
- beautifulsoup
- filter
- iframe
- docker-compose
- design-patterns
- aws-lambda
- text
- visual-c++
- django-rest-framework
- cakephp
- mobile
- android-intent
- struct
- react-hooks
- methods
- groovy
- mvvm
- lambda
- ssh
- time
- checkbox
- ecmascript-6
- grails
- google-chrome-extension
- installation
- cmake
- sharepoint
- shiny
- spring-security
- jakarta-ee
- plsql
- android-recyclerview
- core-data
- types
- sed
- meteor
- android-activity
- bootstrap-4
- activerecord
- websocket
- replace
- graph
- group-by
- scikit-learn
- vim
- file-upload
- boost
- junit
- memory-management
- sass
- async-await
- import
- deep-learning
- error-handling
- eloquent
- dynamic
- dependency-injection
- soap
- silverlight
- layout
- apache-spark-sql
- charts
- deployment
- browser
- gridview
- svn
- while-loop
- google-bigquery
- vuejs2
- highcharts
- dll
- ffmpeg
- view
- foreach
- makefile
- plugins
- redis
- c\#-4.0
- reporting-services
- jupyter-notebook
- unicode
- merge
- reflection
- https
- server
- google-maps-api-3
- twitter
- oauth-2.0
- extjs
- terminal
- axios
- pip
- split
- cmd
- pytorch
- encoding
- django-views
- collections
- database-design
- hash
- netbeans
- automation
- ember.js
- data-binding
- build
- tcp
- pdo
- sqlalchemy
- apache-flex
- entity-framework-core
- concurrency
- command-line
- spring-data-jpa
- printing
- react-redux
- java-8
- lua
- html-table
- neo4j
- ansible
- service
- mysqli
- jestjs
- enums
- parameters
- flexbox
- material-ui
- module
- promise
- visual-studio-2012
- outlook
- web-applications
- uwp
- firebase-authentication
- webview
- jquery-mobile
- utf-8
- datatable
- python-requests
- parallel-processing
- colors
- drop-down-menu
- scipy
- scroll
- tfs
- hive
- count
- syntax
- ms-word
- twitter-bootstrap-3
- ssis
- fonts
- rxjs
- constructor
- google-analytics
- file-io
- paypal
- three.js
- powerbi
- graphql
- cassandra
- discord
- graphics
- compiler-errors
- gwt
- react-router
- socket.io
- backbone.js
- solr
- memory-leaks
- url-rewriting
- datatables
- nlp
- terraform
- oauth
- datagridview
- drupal
- zend-framework
- oracle11g
- triggers
- knockout.js
- neural-network
- interface
- django-forms
- angular-material
- casting
- jmeter
- linked-list
- google-api
- path
- timer
- arduino
- django-templates
- orm
- proxy
- directory
- windows-phone-7
- parse-platform
- visual-studio-2015
- cron
- conditional-statements
- push-notification
- functional-programming
- primefaces
- pagination
- model
- jar
- xamarin.android
- hyperlink
- uiview
- vbscript
- visual-studio-2013
- google-cloud-functions
- azure-active-directory
- gitlab
- jwt
- download
- swift3
- sql-server-2005
- process
- pygame
- rspec
- configuration
- properties
- combobox
- callback
- windows-phone-8
- linux-kernel
- safari
- scrapy
- permissions
- emacs
- x86
- clojure
- scripting
- raspberry-pi
- io
- scope
- azure-functions
- compilation
- expo
- responsive-design
- mongodb-query
- nhibernate
- angularjs-directive
- reference
- binding
- bluetooth
- request
- architecture
- dns
- playframework
- pyqt
- 3d
- version-control
- discord.js
- doctrine-orm
- package
- f\#
- rubygems
- get
- sql-server-2012
- autocomplete
- tree
- openssl
- datepicker
- kendo-ui
- jackson
- yii
- controller
- grep
- nested
- xamarin.ios
- static
- null
- transactions
- statistics
- datagrid
- active-directory
- dockerfile
- uiviewcontroller
- webforms
- sas
- discord.py
- computer-vision
- phpmyadmin
- notifications
- duplicates
- pycharm
- mocking
- youtube
- yaml
- nullpointerexception
- menu
- blazor
- sum
- plotly
- bitmap
- visual-studio-2008
- asp.net-mvc-5
- floating-point
- css-selectors
- yii2
- stl
- electron
- android-listview
- jsf-2
- time-series
- cryptography
- ant
- hashmap
- character-encoding
- stream
- msbuild
- asp.net-core-mvc
- sdk
- google-drive-api
- jboss
- selenium-chromedriver
- joomla
- devise
- navigation
- cors
- cuda
- anaconda
- frontend
- background
- multiprocessing
- binary
- pyqt5
- camera
- iterator
- linq-to-sql
- mariadb
- onclick
- android-jetpack-compose
- ios7
- microsoft-graph-api
- android-asynctask
- rabbitmq
- tabs
- amazon-dynamodb
- laravel-4
- environment-variables
- uicollectionview
- insert
- linker
- xsd
- coldfusion
- console
- continuous-integration
- upload
- textview
- ftp
- opengl-es
- operating-system
- macros
- mockito
- localization
- formatting
- xml-parsing
- json.net
- type-conversion
- vuejs3
- data.table
- kivy
- timestamp
- integer
- calendar
- segmentation-fault
- android-ndk
- prolog
- drag-and-drop
- char
- crash
- jasmine
- dependencies
- geometry
- automated-tests
- azure-pipelines
- fortran
- android-gradle-plugin
- itext
- sprite-kit
- mfc
- header
- attributes
- nosql
- firebase-cloud-messaging
- format
- nuxt.js
- odoo
- db2
- jquery-plugins
- event-handling
- julia
- jenkins-pipeline
- leaflet
- annotations
- flutter-layout
- nestjs
- keyboard
- postman
- textbox
- arm
- stripe-payments
- visual-studio-2017
- gulp
- libgdx
- uikit
- synchronization
- timezone
- azure-web-app-service
- dom-events
- wso2
- xampp
- crystal-reports
- google-sheets-formula
- namespaces
- aggregation-framework
- swagger
- uiscrollview
- android-emulator
- jvm
- sequelize.js
- chart.js
- com
- snowflake-cloud-data-platform
- subprocess
- geolocation
- webdriver
- html5-canvas
- garbage-collection
- sql-update
- centos
- dialog
- concatenation
- numbers
- widget
- qml
- tuples
- set
- java-stream
- mapreduce
- ionic2
- smtp
- windows-10
- rotation
- android-edittext
- nuget
- spring-data
- modal-dialog
- radio-button
- doctrine
- http-headers
- grid
- lucene
- sonarqube
- xmlhttprequest
- listbox
- switch-statement
- initialization
- internationalization
- components
- boolean
- apache-camel
- google-play
- gdb
- serial-port
- ios5
- ldap
- return
- youtube-api
- pivot
- latex
- eclipse-plugin
- tags
- frameworks
- containers
- c++17
- github-actions
- subquery
- dataset
- embedded
- foreign-keys
- asp-classic
- label
- uinavigationcontroller
- delegates
- copy
- google-cloud-storage
- struts2
- migration
- protractor
- base64
- uibutton
- queue
- find
- sql-server-2008-r2
- arguments
- composer-php
- append
- jaxb
- stack
- zip
- tailwind-css
- cucumber
- autolayout
- ide
- entity-framework-6
- iteration
- popup
- r-markdown
- windows-7
- vb6
- airflow
- g++
- clang
- ssl-certificate
- hover
- jqgrid
- range
- gmail
Next
Youâll be prompted to create an account to view your personalized homepage.
1. 1. [Home](https://stackoverflow.com/)
2. [Questions](https://stackoverflow.com/questions)
3. [AI Assist](https://stackoverflow.com/ai-assist)
4. [Tags](https://stackoverflow.com/tags)
5. [Challenges](https://stackoverflow.com/beta/challenges)
6. [Chat](https://chat.stackoverflow.com/?tab=explore)
7. [Articles](https://stackoverflow.blog/contributed?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=so-blog&utm_content=experiment-articles)
8. [Users](https://stackoverflow.com/users)
9. [Companies](https://stackoverflow.com/jobs/companies?so_medium=stackoverflow&so_source=SiteNav)
10. [Collectives]()
11. Communities for your favorite technologies. [Explore all Collectives](https://stackoverflow.com/collectives-all)
2. Stack Internal
Stack Overflow for Teams is now called **Stack Internal**. Bring the best of human thought and AI automation together at your work.
[Try for free](https://stackoverflowteams.com/teams/create/free/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams) [Learn more](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams)
3. [Stack Internal]()
4. Bring the best of human thought and AI automation together at your work. [Learn more](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams-compact)
##### Collectives⢠on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
[Learn more about Collectives](https://stackoverflow.com/collectives)
**Stack Internal**
Knowledge at work
Bring the best of human thought and AI automation together at your work.
[Explore Stack Internal](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams-compact-popover)
# [Remove NaN value from a set](https://stackoverflow.com/questions/37147735/remove-nan-value-from-a-set)
[Ask Question](https://stackoverflow.com/questions/ask)
Asked
9 years, 8 months ago
Modified [2 years, 5 months ago](https://stackoverflow.com/questions/37147735/remove-nan-value-from-a-set?lastactivity "2023-08-02 08:14:04Z")
Viewed 28k times
This question shows research effort; it is useful and clear
26
Save this question.
Show activity on this post.
Is it possible to easily remove NaN values for a Python Set object? Given that NaN values do not equal anything (and `float('nan') is float('nan')` is also `False`), you can end up with many NaN values in a Set.
```
Copy
```
The best I can come up with it to define a function like math.isnan, but that is tolerant of non-float types like:
```
Copy
```
Then you can use a set comprehension like this:
```
Copy
```
- [python](https://stackoverflow.com/questions/tagged/python "show questions tagged 'python'")
[Share](https://stackoverflow.com/q/37147735 "Short permalink to this question")
Share a link to this question
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this question](https://stackoverflow.com/posts/37147735/edit)
Follow
Follow this question to receive notifications
asked May 10, 2016 at 19:52
[](https://stackoverflow.com/users/1231055/brad-campbell)
[Brad Campbell](https://stackoverflow.com/users/1231055/brad-campbell)
3,11122 gold badges2525 silver badges2525 bronze badges
6
- 1
Putting NaNs in a set in the first place is a bad idea. They violate the assumptions a set is built upon.
user2357112
â [user2357112](https://stackoverflow.com/users/2357112/user2357112 "286,393 reputation")
2016-05-10 19:56:36 +00:00
[Commented May 10, 2016 at 19:56](https://stackoverflow.com/questions/37147735/remove-nan-value-from-a-set#comment61833556_37147735)
- What is the question?
Valentin Lorentz
â [Valentin Lorentz](https://stackoverflow.com/users/539465/valentin-lorentz "9,782 reputation")
2016-05-10 20:25:45 +00:00
[Commented May 10, 2016 at 20:25](https://stackoverflow.com/questions/37147735/remove-nan-value-from-a-set#comment61834501_37147735)
- @ValentinLorentz Maybe the sentence that ends with a question mark?
Stefan Pochmann
â [Stefan Pochmann](https://stackoverflow.com/users/1672429/stefan-pochmann "29,019 reputation")
2016-05-10 20:27:10 +00:00
[Commented May 10, 2016 at 20:27](https://stackoverflow.com/questions/37147735/remove-nan-value-from-a-set#comment61834544_37147735)
- @StefanPochmann It is answered at the end of the post
Valentin Lorentz
â [Valentin Lorentz](https://stackoverflow.com/users/539465/valentin-lorentz "9,782 reputation")
2016-05-10 20:29:00 +00:00
[Commented May 10, 2016 at 20:29](https://stackoverflow.com/questions/37147735/remove-nan-value-from-a-set#comment61834599_37147735)
- 1
@user2357112 Yes, that was my conclusion. If you can't test something for equality, you can't really use them in sets. But, other than defining a function like in the question, I could not find another way to get them out of a set.
Brad Campbell
â [Brad Campbell](https://stackoverflow.com/users/1231055/brad-campbell "3,111 reputation")
2016-05-10 20:38:04 +00:00
[Commented May 10, 2016 at 20:38](https://stackoverflow.com/questions/37147735/remove-nan-value-from-a-set#comment61834904_37147735)
\| [Show **1** more comment](https://stackoverflow.com/questions/37147735/remove-nan-value-from-a-set "Expand to show all comments on this post")
## 5 Answers 5
Sorted by:
[Reset to default](https://stackoverflow.com/questions/37147735/remove-nan-value-from-a-set?answertab=scoredesc#tab-top)
This answer is useful
21
Save this answer.
Show activity on this post.
In practice, you could look at the fact that `nan != nan` as a feature, not a bug:
```
Copy
```
On the positive side, no need for a helper function. On the negative side, if you have a non-nan object which is also not equal to itself, you'll remove that too.
[Share](https://stackoverflow.com/a/37148508 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/37148508/edit)
Follow
Follow this answer to receive notifications
answered May 10, 2016 at 20:36
[](https://stackoverflow.com/users/487339/dsm)
[DSM](https://stackoverflow.com/users/487339/dsm)
355k6767 gold badges606606 silver badges504504 bronze badges
Sign up to request clarification or add additional context in comments.
## 1 Comment
Add a comment
[](https://stackoverflow.com/users/1231055/brad-campbell)
Brad Campbell
[Brad Campbell](https://stackoverflow.com/users/1231055/brad-campbell)
[Over a year ago](https://stackoverflow.com/questions/37147735/remove-nan-value-from-a-set#comment61835098_37148508)
I knew there had to be some way with resorting to the helper function. Thanks\!
2016-05-10T20:43:04.593Z+00:00
0
Reply
- Copy link
This answer is useful
8
Save this answer.
Show activity on this post.
Use [pd.notna()](https://pandas.pydata.org/docs/reference/api/pandas.notna.html#pandas.notna) from pandas, e.g.:
```
Copy
```
[Share](https://stackoverflow.com/a/53346628 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/53346628/edit)
Follow
Follow this answer to receive notifications
[edited Oct 9, 2022 at 16:36](https://stackoverflow.com/posts/53346628/revisions "show all edits to this post")
answered Nov 16, 2018 at 23:20
[](https://stackoverflow.com/users/3523176/pawel-kranzberg)
[Pawel Kranzberg](https://stackoverflow.com/users/3523176/pawel-kranzberg)
1,3291616 silver badges1717 bronze badges
## Comments
Add a comment
This answer is useful
4
Save this answer.
Show activity on this post.
Also you can use `filter`:
```
Copy
```
[Share](https://stackoverflow.com/a/37148509 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/37148509/edit)
Follow
Follow this answer to receive notifications
answered May 10, 2016 at 20:36
[](https://stackoverflow.com/users/2635790/ej-f)
[ej\_f](https://stackoverflow.com/users/2635790/ej-f)
46033 silver badges99 bronze badges
## Comments
Add a comment
This answer is useful
3
Save this answer.
Show activity on this post.
We can simply use the .remove() method
```
Copy
```
[Share](https://stackoverflow.com/a/64380141 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/64380141/edit)
Follow
Follow this answer to receive notifications
[edited Oct 22, 2020 at 11:23](https://stackoverflow.com/posts/64380141/revisions "show all edits to this post")
answered Oct 15, 2020 at 21:49
[](https://stackoverflow.com/users/14459006/beno%C3%AEt-lebreton)
[BenoĂŽt Lebreton](https://stackoverflow.com/users/14459006/beno%C3%AEt-lebreton)
4122 bronze badges
## 3 Comments
Add a comment
[](https://stackoverflow.com/users/5604562/grayrigel)
Grayrigel
[Grayrigel](https://stackoverflow.com/users/5604562/grayrigel)
[Over a year ago](https://stackoverflow.com/questions/37147735/remove-nan-value-from-a-set#comment113842952_64380141)
Please consider add some explanation/comments to the code.
2020-10-15T22:47:25.62Z+00:00
1
Reply
- Copy link
[](https://stackoverflow.com/users/3523176/pawel-kranzberg)
Pawel Kranzberg
[Pawel Kranzberg](https://stackoverflow.com/users/3523176/pawel-kranzberg)
[Over a year ago](https://stackoverflow.com/questions/37147735/remove-nan-value-from-a-set#comment114958460_64380141)
As @Fre\_der\_ik noted, `remove()` will raise an error if there is no NaN in the set. Use `discard()` instead.
2020-11-26T15:13:12.77Z+00:00
2
Reply
- Copy link
[](https://stackoverflow.com/users/11112772/md-sabbir-ahmed)
Md Sabbir Ahmed
[Md Sabbir Ahmed](https://stackoverflow.com/users/11112772/md-sabbir-ahmed)
[Over a year ago](https://stackoverflow.com/questions/37147735/remove-nan-value-from-a-set#comment117007707_64380141)
@BenoĂŽt Lebreton Your answer helped me a lot.
2021-02-13T07:33:12.087Z+00:00
0
Reply
- Copy link
Add a comment
This answer is useful
0
Save this answer.
Show activity on this post.
I cannot make a comment, so I combine the answers above, with some explanation (for beginners). Create a set, including NaN (numpy.nan value)
```
Copy
```
Check the created set as result:
```
Copy
```
Discard (better then remove which could lead to KeyError if there is non NaN in the set) NaNs:
```
CopyIn[4]: a.discard(np.nan)
```
Check the result:
```
Copy
```
[Share](https://stackoverflow.com/a/76817869 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/76817869/edit)
Follow
Follow this answer to receive notifications
answered Aug 2, 2023 at 8:14
[](https://stackoverflow.com/users/19204830/qmcm)
[QMCM](https://stackoverflow.com/users/19204830/qmcm)
4144 bronze badges
## Comments
Add a comment
Start asking to get answers
Find the answer to your question by asking.
[Ask question](https://stackoverflow.com/questions/ask)
Explore related questions
- [python](https://stackoverflow.com/questions/tagged/python "show questions tagged 'python'")
See similar questions with these tags.
- The Overflow Blog
- [If you're a Zoomer, this one's for you: Everything Gen Z needs to know about...](https://stackoverflow.blog/2026/01/14/gen-z-wrapped-2025/?cb=1 "If you're a Zoomer, this one's for you: Everything Gen Z needs to know about the 2025 tech landscape")
- [How Stack Overflow is taking on spam and bad actors](https://stackoverflow.blog/2026/01/15/how-stack-overflow-is-taking-on-spam-and-bad-actors/?cb=1)
- Featured on Meta
- [A proposal for bringing back Community Promotion & Open Source Ads](https://meta.stackexchange.com/questions/416429/a-proposal-for-bringing-back-community-promotion-open-source-ads?cb=1)
- [Community Asks Sprint Announcement â January 2026: Custom site-specific badges\!](https://meta.stackexchange.com/questions/416734/community-asks-sprint-announcement-january-2026-custom-site-specific-badges?cb=1)
- [Policy: Generative AI (e.g., ChatGPT) is banned](https://meta.stackoverflow.com/questions/421831/policy-generative-ai-e-g-chatgpt-is-banned?cb=1)
- [All users on Stack Overflow can now participate in chat](https://meta.stackoverflow.com/questions/437932/all-users-on-stack-overflow-can-now-participate-in-chat?cb=1)
- [Should Stack Overflow utilize machine learning anti-spam?](https://meta.stackoverflow.com/questions/437959/should-stack-overflow-utilize-machine-learning-anti-spam?cb=1)
Community activity
Last 1 hr
- Users online activity
4989 users online
- 9 questions
- 8 answers
- 21 comments
- 83 upvotes
Popular tags
[sql](https://stackoverflow.com/questions/tagged/sql)[mysql](https://stackoverflow.com/questions/tagged/mysql)[java](https://stackoverflow.com/questions/tagged/java)[python](https://stackoverflow.com/questions/tagged/python)[prisma](https://stackoverflow.com/questions/tagged/prisma)
#### Linked
[2](https://stackoverflow.com/questions/45978058/return-nan-from-indexing-operation-on-a-pandas-series?lq=1 "Question score (upvotes - downvotes)")
[Return NaN from indexing operation on a pandas series](https://stackoverflow.com/questions/45978058/return-nan-from-indexing-operation-on-a-pandas-series?noredirect=1&lq=1)
#### Related
[5664](https://stackoverflow.com/questions/522563/how-can-i-access-the-index-value-in-a-for-loop?rq=1 "Question score (upvotes - downvotes)")
[How can I access the index value in a 'for' loop?](https://stackoverflow.com/questions/522563/how-can-i-access-the-index-value-in-a-for-loop?rq=1)
[3013](https://stackoverflow.com/questions/11277432/how-can-i-remove-a-key-from-a-python-dictionary?rq=1 "Question score (upvotes - downvotes)")
[How can I remove a key from a Python dictionary?](https://stackoverflow.com/questions/11277432/how-can-i-remove-a-key-from-a-python-dictionary?rq=1)
[3413](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value?rq=1 "Question score (upvotes - downvotes)")
[How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value?rq=1)
[2345](https://stackoverflow.com/questions/627435/how-to-remove-an-element-from-a-list-by-index?rq=1 "Question score (upvotes - downvotes)")
[How to remove an element from a list by index](https://stackoverflow.com/questions/627435/how-to-remove-an-element-from-a-list-by-index?rq=1)
[1723](https://stackoverflow.com/questions/944700/how-to-check-for-nan-values?rq=1 "Question score (upvotes - downvotes)")
[How to check for NaN values](https://stackoverflow.com/questions/944700/how-to-check-for-nan-values?rq=1)
[3628](https://stackoverflow.com/questions/17071871/how-do-i-select-rows-from-a-dataframe-based-on-column-values?rq=1 "Question score (upvotes - downvotes)")
[How do I select rows from a DataFrame based on column values?](https://stackoverflow.com/questions/17071871/how-do-i-select-rows-from-a-dataframe-based-on-column-values?rq=1)
[2077](https://stackoverflow.com/questions/275018/how-can-i-remove-a-trailing-newline?rq=1 "Question score (upvotes - downvotes)")
[How can I remove a trailing newline?](https://stackoverflow.com/questions/275018/how-can-i-remove-a-trailing-newline?rq=1)
[2663](https://stackoverflow.com/questions/4383571/importing-files-from-different-folder?rq=1 "Question score (upvotes - downvotes)")
[Importing files from different folder](https://stackoverflow.com/questions/4383571/importing-files-from-different-folder?rq=1)
[1477](https://stackoverflow.com/questions/13413590/how-to-drop-rows-of-pandas-dataframe-whose-value-in-a-certain-column-is-nan?rq=1 "Question score (upvotes - downvotes)")
[How to drop rows of Pandas DataFrame whose value in a certain column is NaN](https://stackoverflow.com/questions/13413590/how-to-drop-rows-of-pandas-dataframe-whose-value-in-a-certain-column-is-nan?rq=1)
#### [Hot Network Questions](https://stackexchange.com/questions?tab=hot)
- [Are achievements bugged in Sludge Life 2?](https://gaming.stackexchange.com/questions/417620/are-achievements-bugged-in-sludge-life-2)
- [Can I pigtail \#14/2 wire off \#8/3 gauge to run 3 receptacles?](https://diy.stackexchange.com/questions/328613/can-i-pigtail-14-2-wire-off-8-3-gauge-to-run-3-receptacles)
- [How is the recursion principle for Acc generated by Rocq?](https://proofassistants.stackexchange.com/questions/6447/how-is-the-recursion-principle-for-acc-generated-by-rocq)
- [Do 40% of Australian teenage boys support âright-wing violent extremismâ?](https://skeptics.stackexchange.com/questions/60427/do-40-of-australian-teenage-boys-support-right-wing-violent-extremism)
- [English idiom about a new item breaking down or getting lost upon acquisition](https://english.stackexchange.com/questions/638603/english-idiom-about-a-new-item-breaking-down-or-getting-lost-upon-acquisition)
- [Could reality exist without logic? Could reality be illogical?](https://philosophy.stackexchange.com/questions/135280/could-reality-exist-without-logic-could-reality-be-illogical)
- [Bending Paper with IK Bones](https://blender.stackexchange.com/questions/344524/bending-paper-with-ik-bones)
- [How to define file-based indentation rules in Kate?](https://unix.stackexchange.com/questions/803767/how-to-define-file-based-indentation-rules-in-kate)
- [Strong Linear Correlation but Highly Patterned Residuals](https://stats.stackexchange.com/questions/674341/strong-linear-correlation-but-highly-patterned-residuals)
- [78xx adjustable voltage circuit not working](https://electronics.stackexchange.com/questions/764456/78xx-adjustable-voltage-circuit-not-working)
- [Another definite integral](https://mathoverflow.net/questions/507034/another-definite-integral)
- [Does GPL require code-sharing to be specific to the product, or can a company lump all GPL software in one non-specific place?](https://opensource.stackexchange.com/questions/15694/does-gpl-require-code-sharing-to-be-specific-to-the-product-or-can-a-company-lu)
- [Why adding titlesec makes links in toc inside PDF no longer work when using \\setcounter{secnumdepth}{0}?](https://tex.stackexchange.com/questions/758333/why-adding-titlesec-makes-links-in-toc-inside-pdf-no-longer-work-when-using-set)
- [Hierarchical lists in ConTeXt?](https://tex.stackexchange.com/questions/758336/hierarchical-lists-in-context)
- [Periodic Updates for User Control Types (E.g. DataGrid/TextBoxes/etc) from DB in WPF with MVVM pattern?](https://softwareengineering.stackexchange.com/questions/460710/periodic-updates-for-user-control-types-e-g-datagrid-textboxes-etc-from-db-in)
- [Files with identical name in the same directory](https://unix.stackexchange.com/questions/803744/files-with-identical-name-in-the-same-directory)
- [Is working on and publishing "grunt math" acceptable as a high school student?](https://academia.stackexchange.com/questions/225638/is-working-on-and-publishing-grunt-math-acceptable-as-a-high-school-student)
- [Origin of âschâ in German writing](https://german.stackexchange.com/questions/82038/origin-of-sch-in-german-writing)
- [What is "social freedom"?](https://politics.stackexchange.com/questions/94073/what-is-social-freedom)
- [Why was Gold 5 apparently giving orders to Gold Leader during the first trench run?](https://scifi.stackexchange.com/questions/302848/why-was-gold-5-apparently-giving-orders-to-gold-leader-during-the-first-trench-r)
- [Interpreting ăăă¸ăŽĺŚĽĺ˝ć§](https://japanese.stackexchange.com/questions/111664/interpreting-%E3%81%9D%E3%82%8C%E3%81%B8%E3%81%AE%E5%A6%A5%E5%BD%93%E6%80%A7)
- [Long term side effect of cryosleep](https://worldbuilding.stackexchange.com/questions/272347/long-term-side-effect-of-cryosleep)
- [What is "interception" of transactions in the BTCPuzzle case?](https://bitcoin.stackexchange.com/questions/130427/what-is-interception-of-transactions-in-the-btcpuzzle-case)
- [How Should I Write a Series of Thoughts being Interrupted?](https://writing.stackexchange.com/questions/72129/how-should-i-write-a-series-of-thoughts-being-interrupted)
[Question feed](https://stackoverflow.com/feeds/question/37147735 "Feed of this question and its answers")
# Subscribe to RSS
Question feed
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

lang-py
# Why are you flagging this comment?
Probable spam.
This comment promotes a product, service or website while [failing to disclose the author's affiliation](https://stackoverflow.com/help/promotion).
Unfriendly or contains harassment/bigotry/abuse.
This comment is unkind, insulting or attacks another person or group. Learn more in our [Abusive behavior policy](https://stackoverflow.com/conduct/abusive-behavior).
Not needed.
This comment is not relevant to the post.
```
```
Enter at least 6 characters
Something else.
A problem not listed above. Try to be as specific as possible.
```
```
Enter at least 6 characters
Flag comment
Cancel
You have 0 flags left today
# 
# Hang on, you can't upvote just yet.
You'll need to complete a few actions and gain 15 reputation points before being able to upvote. **Upvoting** indicates when questions and answers are useful. [What's reputation and how do I get it?](https://stackoverflow.com/help/whats-reputation)
Instead, you can save this post to reference later.
Save this post for later
Not now
##### [Stack Overflow](https://stackoverflow.com/)
- [Questions](https://stackoverflow.com/questions)
- [Help](https://stackoverflow.com/help)
- [Chat](https://chat.stackoverflow.com/?tab=explore)
##### [Business](https://stackoverflow.co/)
- [Stack Internal](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=footer&utm_content=teams)
- [Stack Data Licensing](https://stackoverflow.co/data-licensing/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=footer&utm_content=data-licensing)
- [Stack Ads](https://stackoverflow.co/advertising/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=footer&utm_content=advertising)
##### [Company](https://stackoverflow.co/)
- [About](https://stackoverflow.co/)
- [Press](https://stackoverflow.co/company/press/)
- [Work Here](https://stackoverflow.co/company/work-here/)
- [Legal](https://stackoverflow.com/legal)
- [Privacy Policy](https://stackoverflow.com/legal/privacy-policy)
- [Terms of Service](https://stackoverflow.com/legal/terms-of-service/public)
- [Contact Us](https://stackoverflow.com/contact)
- Cookie Settings
- [Cookie Policy](https://policies.stackoverflow.co/stack-overflow/cookie-policy)
##### [Stack Exchange Network](https://stackexchange.com/)
- [Technology](https://stackexchange.com/sites#technology)
- [Culture & recreation](https://stackexchange.com/sites#culturerecreation)
- [Life & arts](https://stackexchange.com/sites#lifearts)
- [Science](https://stackexchange.com/sites#science)
- [Professional](https://stackexchange.com/sites#professional)
- [Business](https://stackexchange.com/sites#business)
- [API](https://api.stackexchange.com/)
- [Data](https://data.stackexchange.com/)
- [Blog](https://stackoverflow.blog/?blb=1)
- [Facebook](https://www.facebook.com/officialstackoverflow/)
- [Twitter](https://twitter.com/stackoverflow)
- [LinkedIn](https://linkedin.com/company/stack-overflow)
- [Instagram](https://www.instagram.com/thestackoverflow)
Site design / logo Š 2026 Stack Exchange Inc; user contributions licensed under [CC BY-SA](https://stackoverflow.com/help/licensing) . rev 2026.1.14.38635 |
| Readable Markdown | null |
| Shard | 169 (laksa) |
| Root Hash | 714406497480128969 |
| Unparsed URL | com,stackoverflow!/questions/37147735/remove-nan-value-from-a-set s443 |