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

Question:

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

Asked By: UltimeCactus

||

Answers:

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))
Answered By: AKX

Facing a similar situation. I suggest you replace the '' with np.nan.

x = ['1.1', '', '2.3', '2.0']

for i, v in enumerate(x):
    if v == '':
        x[i] = np.nan
    else:
        x[i] = float(v)

print(x)
[1.1, nan, 2.3, 2.0]

Curiously, I find out that it works only if x is list. It doesn’t work with numpy arrays!

Maybe there is a ‘comprehension list’ way to do that.

Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.