【发布时间】:2023-03-28 08:25:01
【问题描述】:
我正在处理一个简单的 csv 文件,该文件包含三列三行,其中包含数字数据。 csv 数据文件如下所示:
Col1,Col2,Col3
1,2,3
2,2,3
3,2,3
4,2,3
我很难弄清楚如何让我的 python 程序从同一列中的每个值中减去第一列“Col1”的平均值。为便于说明,输出应为“Col1”提供以下值:
1 - 2.5 = -1.5
2 - 2.5 = -0.5
3 - 2.5 = 0.5
4 - 2.5 = 1.5
这是我的尝试,它给了我 (TypeError: unsupported operand type(s) for -: 'str' and 'float' ) 在包含理解的最后一个打印语句中。
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'
我不知道如何解决这个问题!知道如何使理解能够给出应该做的事情吗?
【问题讨论】:
-
错误说你不能做一个字符串减去一个浮点数。有问题的行有
e-Aver。因此,e是一个字符串,Aver是一个浮点数。因此,您必须将e转换为浮点数。
标签: python csv list-comprehension typeerror arithmetic-expressions