我正在处理一个简单的 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'
不知道如何解决这个问题!知道如何使理解发挥应有的作用吗?
最佳答案
代码中的问题是,在 data
列表 (file2
) 的情况下,您正在从文件中读取字符串并将字符串存储到 data
列表。
因此,当稍后您尝试执行 - [e-Aver for e in data]
- 当您尝试从字符串中减去 float 时,它会出错。
在存储到data
列表之前,您应该转换为float
或int
。示例-
data = []
for row in file2:
data.append(float(row['Col1']))
关于python - 如何在推导式中正确使用算术运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33050100/