Quick question for an issue I haven't managed to solve quickly:
I'm working with a .csv file and can't seem to find a simple way to convert strings to floats. Here's my code,
import csv
def readLines():
with open('testdata.csv', 'rU') as data:
reader = csv.reader(data)
row = list(reader)
for x in row:
for y in x:
print type(float(y)),
readLines()
As you can see, it will currently print the type of every y element in x set of lists in the variable row; this produces a long list of "<type 'float'>"
. But this doesn't actually change each element to a float, nor does setting the for loop to execute float(y)
(a type test returns 'string' for each element) work either.
I also tried literal_eval, but that failed as well. The only way to change the list elements to floats is to create a new list, either with list comprehension or manually, but that loses the original formatting of each list (as lists of a set amount of elements within one larger list).
I suppose the overall question is really just "What's the easiest way to read, organize, and synthesize data in .csv or excel format using Python?"
Thanks in advance to those courteous/knowledgeable enough to help.
y = float(y)
– Culmiferousimport csv
is different to usingpandas
. Essentially, the builtin csv module is broken and should not be used on any non-toy dataset containing one or more text or categorical fields. Use pandas. – Kuykendall