Reputation: 321
I'm using this function to read in a csv file but I want to convert it from strings to floats. I'm not sure where to insert. When I try I usually get an error that ' float' object has no attribute 'getitem'
def getColumn(filename, column):
results = csv.reader(open(filename), delimiter=',')
next(results, None)
return [result[column] for result in results]
Upvotes: 0
Views: 8058
Reputation: 48599
import csv
def get_column(filename, column):
with open(filename) as f:
reader = csv.DictReader(f)
results = []
for row in reader:
entry = row[column]
try:
results.append(float(entry))
except ValueError:
print(
"Could not convert '{}' to "
"a float...skipping.".format(entry)
)
return results
result = get_column('csv.csv', 'num')
print(result)
print(sum(result))
--output:--
Could not convert 'mars' to a float...skipping.
[3.1, 2.6]
5.7
Upvotes: 1
Reputation: 6059
I suppose, you are using Python. You can simply parse a String to a float, such as:
a = "42.23"
float(a)
Upvotes: 0