Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String in list to float

I have a list called 'ft_List that looks like...

[['Fall2001', '22.00', '2000', '01', '01', '120.0', '', 'N'], 
[CgeCam2002', '20.00', '2000', '09', '04', '0.0', '1', ''],
['Fall2004', '18.50', '2001', '18', '01', '', '', 'Y']........

...how can I convert column 5 to floats? I tried

for i in ft_Rec:
    ms = i[5].split(',')
    float(ms)

but get

TypeError: float() argument must be a string or number

. I thought it was a string? Is it because some fields are empty (' ')? I'd like to perform some calculations with this column

like image 782
user2395759 Avatar asked Aug 09 '26 07:08

user2395759


2 Answers

You don't need to split this input, it is already a list, just check for empty string:

for i in ft_Rec:
    if i[5]: print float(i[5])

To get the total:

total = sum( float(i[5]) for i in ft_Rec if i[5] )
like image 101
perreal Avatar answered Aug 11 '26 21:08

perreal


>>> ft_List = [['Fall2001', '22.00', '2000', '01', '01', '120.0', '', 'N'],
['CgeCam2002', '20.00', '2000', '09', '04', '0.0', '1', ''],
['Fall2004', '18.50', '2001', '18', '01', '', '', 'Y']]
>>> for i in ft_List:
        i[5] = float(i[5] or 0) # empty string logical ors to 0


>>> ft_List
[['Fall2001', '22.00', '2000', '01', '01', 120.0, '', 'N'], ['CgeCam2002', '20.00', '2000', '09', '04', 0.0, '1', ''], ['Fall2004', '18.50', '2001', '18', '01', 0.0, '', 'Y']]

The problem is:

>>> float('')

Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    float('')
ValueError: could not convert string to float: 

This solution just uses that fact that empty built-in objects in Python evaluate as False

>>> '' or 0
0
like image 20
jamylak Avatar answered Aug 11 '26 21:08

jamylak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!