Search code examples
pythonstringnanminis-empty

Python : Convert list of strings to floats with empty/none


I have a = ['1','2','','17']

I would like to apply a min / max operation on it. I can't use pandas/numpy.

I convert it to a float, however, but I can't convert '' to floats with the float() function. Same thing happens if I have a None rather than a ''.

I never faced this problem in matlab so I'm lost with python.

I can convert it into a float with [float(i) for i in var if i], but I need to keep the same size to work on index later. This method will remove the empty strings, it is not what I want, I need a value (apparently not a None) that I could apply mean/max/min etc on it


Solution

  • You could define a function that tries to convert values to floats and returns None if it can't, then use list comprehensions to create converted and filtered versions of the list you can use min/max/... whatever on while keeping the original intact.

    def try_float(v):
       try:
           return float(v)
       except Exception:
           return None
    
    # Original:
    a = ['1', '2', '', '17', None, 'purple', -7, 0]
    
    # Containing floats and Nones:
    floaty_a = [try_float(item) for item in a]
    
    # Filter out the Nones:
    filtered_a = [item for item in floaty_a if item is not None]
    
    # Compute min/max:
    print(min(filtered_a))
    print(max(filtered_a))