python - How to Properly Use Arithmetic Operators Inside Comprehensions? -
i dealing simple csv file contains 3 columns , 3 rows containing numeric data. csv data file looks following:
col1,col2,col3 1,2,3 2,2,3 3,2,3 4,2,3
i have hard time figuring out how let python program subtracts average value of first column "col1" each value in same column. illustration output should give following values 'col1':
1 - 2.5 = -1.5 2 - 2.5 = -0.5 3 - 2.5 = 0.5 4 - 2.5 = 1.5
here attempt gives me (typeerror: unsupported operand type(s) -: 'str' , 'float' ) @ last print statement containing comprehension.
import csv # opening csv file file1 = csv.dictreader(open('columns.csv')) file2 = csv.dictreader(open('columns.csv')) # calculations numofsamples = open('columns.csv').read().count('\n') sumdata = sum(float(row['col1']) row in file1) aver = sumdata/(numofsamples - 1) # compute average of data in 'col1' # subtracting average each value in 'col1' data = [] row in file2: data.append(row['col1']) # print results print aver print [e-aver e in data] # trying use comprehension subtract average each value in list 'data'
i not know how solve problem! idea how make comprehension working give supposed do?
the issue in code in case of data
list (file2
) , reading strings file , storing strings data
list.
hence, when later on , try - [e-aver e in data]
- errors out trying subtract float string.
you should convert float
or int
before storing data
list. example -
data = [] row in file2: data.append(float(row['col1']))
Comments
Post a Comment