Ask Your Question

How to drop 'NAN' values from a list

asked 2020-08-06 06:33:51 -0600

Cyrille gravatar image

updated 2020-08-06 07:57:07 -0600

I rewrite my question : I have the followinbg list z=[-1, 0, 1, 2, 3, 'Toto'] and I want to create a list composqe of strictly positive numbers (whichever type they are) and without toto

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2020-08-06 07:16:21 -0600

slelievre gravatar image

updated 2020-08-06 09:11:13 -0600

The question is about filtering a list, keeping only those elements in the list that correspond to positive numbers.

This means filtering out all elements that are not positive numbers.

In particular all strings must be filtered out.

If the list is known to consist only of numbers and 'NAN', or only of numbers and any strings, it is easy to filter out strings.

To exclude values that are equal to the string 'NAN':

 zz = [x for x in z if x != 'NAN' and x > 0]

To exclude all strings:

zz = [x for x in z if not isinstance(x, str) and x > 0]

If list elements can be anything, first check which elements are real numbers, and test positivity for those.

import numbers
zz = [x for x in z if isinstance(x, numbers.Real) and x > 0]
edit flag offensive delete link more


I rewrite my question

Cyrille gravatar imageCyrille ( 2020-08-06 07:43:48 -0600 )edit

Thanks it's exactly what I was searching but on the way I have had an other idea to obtain what I was searching and I have encountered a new difficulty so I am going to ask a new question. Sorry and 1000000 thanks for your help.

Cyrille gravatar imageCyrille ( 2020-08-06 11:53:18 -0600 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2020-08-06 06:33:51 -0600

Seen: 79 times

Last updated: Aug 06 '20