4

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

UltimeCactus
  • 73
  • 1
  • 6

2 Answers2

4

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))
AKX
  • 152,115
  • 15
  • 115
  • 172
  • Thanks for your answer, it's similar to what I want (the floaty_a) so I can apply index position later on it – UltimeCactus Feb 04 '20 at 12:38
  • if you're using Pandas, you can use df['MyColumn'] = df['MyColumn'].astype(float) This will take care of None automatically – Jelmer Wind Sep 07 '21 at 08:09
0

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.