3

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

2
  • even without split i get the same error Commented May 24, 2013 at 5:05
  • 1
    note that float(ms) doesn't modify your list: you need i[5] = float(ms) Commented May 24, 2013 at 5:34

4 Answers 4

3

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] )
Sign up to request clarification or add additional context in comments.

1 Comment

Cool, thanks. It seems to print all as floats but where do I put sum(i[5])? If its within the for loop, it says float() not iterable
1
>>> 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

2 Comments

I qualified your "empty objects in Python evaluate as False": this is true for built-in objects, but is not required from user classes (which by default even evaluate to True even when "empty"!).
@EOL thanks, I was originally going to go with that but thought it made it too complicated
0

you may do like this:

>>> for row in ll:
...     f = float(row[5]) if row[5] else 0.
...     print f
... 
120.0
0.0
0.0

where ll is:

>>> ll = [['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']]

I am printing 0.0 for empty strings ''

Comments

-1

python doesnot accept empty strings as argument for floats.

    >>>float(' ')
    >>>ValueError: could not convert string to float:

1 Comment

The question is "how can I convert column 5 to floats?"…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.