-2

I have an array that can be simplified to something like this:

a=[nan, 2, 1, 1, nan, nan, 3, nan, nan, 3, 4, 7, 8, 9, 8, 7, 7, nan, nan, nan, 3, 2, nan, 2]

I would like to keep the elements 3, 4, 7, 8, 9, 8, 7, 7 the nan elements don't bother me because they don't show up in the graphic, but I would like to filter the rest of the values.

Criteria: Longest sequence without a nan

Ricardo Fumachi
  • 79
  • 1
  • 11

3 Answers3

2

This is an excellent place for a list comprehension.

The syntax is as follows: [x for x in my_list if condition()]

So, assuming your criteria are x is nan or x>=3:

from math import isnan
filtered_list = [x for x in my_list if isnan(x) or x >=3]

Note that nan behaves unusually: for any variable v, (nan==v)==False . Use math.isnan instead.

Efron Licht
  • 488
  • 3
  • 13
2

Substantially edited since the question is clarified.

To get the longest sequence you can use groupby and max:

>>> from itertools import groupby
>>> from math import isnan

>>> nan = float('NaN')

>>> a = [nan, 2, 1, 1, nan, nan, 3, nan, nan, 3, 4, 7, 8,
...      9, 8, 7, 7, nan, nan, nan, 3, 2, nan, 2]

>>> max((list(group) for key, group in groupby(a, key=isnan)), key=len)
[3, 4, 7, 8, 9, 8, 7, 7]
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
-1

You could just try

     a = a[9:-7]

after your current code...

See Colon (:) in Python list index for explanation

Community
  • 1
  • 1
valleymanbs
  • 487
  • 3
  • 14