I wanna converts all strings in numeric columns 2-3 ("weight" and "age") to a number or None.
data = [('marvin', 'dog', 25, "1"),
('garfield', 'cat', "N/A", 8),
('rosie', 'cat', 14, None),
('fred', 'dog', 20, "7")]
I wanna use try/except type but got stuck.
This is my code:
output1 = []
for d in data:
try:
foo = (d[0], d[1], float(d[2]), float(d[3]))
output1.append(foo)
except:
output1.append((d[0], d[1], None, None))
output1
Expected results should be:
[('marvin', 'dog', 25.0, 1.0),
('garfield', 'cat', None, 8.0),
('rosie', 'cat', 14.0, None),
('fred', 'dog', 20.0, 7.0)]
But I got:
[('marvin', 'dog', 25.0, 1.0),
('garfield', 'cat', None, None),
('rosie', 'cat', None, None),
('fred', 'dog', 20.0, 7.0)]