简体   繁体   中英

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

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))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM