I am dealing with a simple csv file that contains three columns and three rows containing numeric data. The csv data file looks like the following:
Col1,Col2,Col3
1,2,3
2,2,3
3,2,3
4,2,3
I have hard time figuring out how to let my python program subtracts the average value of the first column "Col1" from each value in the same column. For illustration the output should give the following values for 'Col1':
1 - 2.5 = -1.5
2 - 2.5 = -0.5
3 - 2.5 = 0.5
4 - 2.5 = 1.5
Here is my attempt that gives me (TypeError: unsupported operand type(s) for -: 'str' and 'float' ) at the last print statement which containing the comprehension.
import csv
# Opening the csv file
file1 = csv.DictReader(open('columns.csv'))
file2 = csv.DictReader(open('columns.csv'))
# Do some calculations
NumOfSamples = open('columns.csv').read().count('\n')
SumData = sum(float(row['Col1']) for row in file1)
Aver = SumData/(NumOfSamples - 1) # compute the average of the data in 'Col1'
# Subtracting the average from each value in 'Col1'
data = []
for row in file2:
data.append(row['Col1'])
# Print the results
print Aver
print [e-Aver for e in data] # trying to use comprehension to subtract the average from each value in the list 'data'
I do not know how to solve this problem! Any idea how to make the comprehension working to give what is supposed to do?