Home > front end >  Return the last not null, nan, and non empty value from a python list
Return the last not null, nan, and non empty value from a python list

Time:11-29

How can I return the last not null, not empty, and not nan from a list? if not exists, then return "null" or a customized message!

I have tried these pieces of codes and none of them is bullet proof:

import numpy as np

listF=[0.0,np. NaN,2,0,0.0,""]
print([j for j in listF if j][-1])#returns 2

listF=[0.0,np. NaN,np. NaN,0,0.0,np. NaN]
print([j for j in listF if j][-1])#returns nan while should return 0


listF=[]
print([j for j in listF if j][-1])#returns Index out of range


listF=[1,np. NaN,np. NaN,0,0.0,np. NaN]
print([j for j in listF if j][-1])#returns nan while should return 0 

listF=[np. NaN,np. NaN,np. NaN]
print([j for j in listF if j][-1])#returns nan while should return "null"

CodePudding user response:

You can use math.isnan (or numpy.isnan) to check the NA status. Combine it with an iterator and a default value to handle cases without valid value:

from math import isnan

def last_valid(lst):
    return next((x for x in reversed(lst) if x and not isnan(x)), None)

last_valid([])
# None

last_valid([0.0,np. NaN,2,0,0.0,""])
# 2

last_valid([1,np. NaN,np. NaN,0,0.0,np. NaN])
# 1

last_valid([0.0,np. NaN,np. NaN,0,0.0,np. NaN])
# None

CodePudding user response:

>>> bool(np.nan)
True
>>> bool('')
False
>>> bool(0.0)
False

A more general method is to create a forbiden set and use it to filter the original list.

fset = set(['', np.nan])
valid_list = [j for j in listF if j not in fset]
  • Related