帮助计算保存为CSV的Excel文件的平均值和标准差
我有大约20个Excel文件,保存为CSV格式,放在一个文件夹里。每个Excel文件的第一、第二和第三列都有数字。我想用Python的CSV模块读取所有文件的第一列、第二列和第三列,然后计算每一列的平均值和标准差,并把这些结果保存到一个单独的Excel文件里。请帮帮我……这是我目前的进展……我该如何单独访问每一列呢?
import csv
import os
from numpy import array
path="A:\\hello\\folder"
dirList=os.listdir(path)
for file in dirList:
fullpath=os.path.join(path,file)
## print fullpath
with open(fullpath, 'rb') as f:
[[val for val in line.split(',')] for line in f.readlines()]
## print line
nums = array([line])
for row in nums:
print row.mean()
1 个回答
2
一个列表推导式就像是一个反向的循环,它可以自动帮你构建一个列表
。如果你把它们嵌套起来,把“列”放在里面,把“行”放在外面,你就能得到一个类似矩阵的东西(嵌套列表结构):
nums = [[int(val) for val in line.split(',')] for line in my_file.readlines()]
或者,如果你有一个csv读取对象,它可能看起来像这样:
nums = [[int(val) for val in line] for line in my_csv_reader]
现在,你通过上面的列表推导式把矩阵存到了一个叫nums
的变量里。
接下来,你可能需要使用numpy来计算一些统计数据。这很方便,因为你可以很容易地访问numpy数组的列,当你这样做时,它会以numpy数组的形式返回该列。numpy数组还内置了计算均值和标准差的方法。你只需把nums
传入array()
构造函数,就可以把它转换成numpy数组:
from numpy import array
anums = array(nums)
然后,如果你想遍历列,可以使用数组切片表示法和每个numpy数组都有的shape
变量:
# The 1 index of anums.shape should tell you how many columns you have
for c in range(anums.shape[1]):
column = anums[:,c]
col_mean = column.mean()
col_std = column.std()
# Do something with these variables here, probably