数据文件中的行均值

尼克·查尔顿

我需要创建一个函数来计算数据文件(.csv)中每行数字的均值,然后将均值作为列表返回。

我设法获得了加在一起的数字的值,但是我不知道如何除以每行数据的长度,然后将结果输入要返回的列表中。

def line_averages(filename):
    """ compute the average value for every line, and return the average
    values in a list in the file "filename" """
    infile = open(filename, "r")
    all_input = infile.read()
    infile.close()
    lines = all_input.split('\n')       # remove lines
    for one_line in lines:
        values = one_line.split(',')    # remove commas
        line_sum = 0 
        print(values)
        for j in values:
            line_sum = line_sum + float(j)

更新:

这是我根据以下建议之一获得的新代码:

def line_averages(filename):
""" compute the average value for every line, and return the average
values in a list in the file "filename" """
f = open(filename, "r")
x = f.read()
f.close()
no_lines = x.split('\n')       # remove lines
means = []
for i in no_lines:
    no_commas = i.split(',')    # remove commas
    average = sum(no_commas) / len(no_commas)
    means.append(average)
return means

我收到此错误:

In [22]: line_averages("data.csv")
Traceback (most recent call last):

File "<ipython-input-29-e2e3fddb5de5>", line 1, in <module>
line_averages("data.csv")

File "E:/Google Drive/python_files/training4.py", line 19, in line_averages
average = sum(no_commas) / len(no_commas)

TypeError: unsupported operand type(s) for +: 'int' and 'str'

不知道出了什么问题?!

修剪
return_list = []
...
    average = sum(values) / len(values)
    return_list.append(average)

另外,使用描述性变量名。单字母变量可以用于一次性索引,但不适用于任何具有持久含义的变量。


扰流板警报

# If you have the statistics package, use "mean" from that, instead.
def mean(coll):
    return float(sum(coll)) / max(len(coll), 1)

def line_averages(filename):
    """ compute the average value for every line, and return the average
    values in a list in the file "filename" """

    return [mean([int(values) for values in line.split(',')]) for line in open(filename)]

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

数据文件“ +不支持的操作数类型:'int'和'str'”行中数字的平均值

来自分类Dev

如何从数据文件gnuplot中的行绘制直方图

来自分类Dev

在for循环中使用find_peaks从数据文件中查找峰高以计算均值

来自分类Dev

从数据文件中读取数据点

来自分类Dev

从数据文件中选择特定的行

来自分类Dev

如何在Linux中根据行中的列数拆分大数据文件中的行?

来自分类Dev

数据文件中的几个图

来自分类Dev

从python包中访问数据文件

来自分类Dev

数据文件中的Python Matplotlib IMShow

来自分类Dev

如何从数据文件中减去常数?

来自分类Dev

数据文件中的分割线

来自分类Dev

数据文件中的几个图

来自分类Dev

在python中解析通用数据文件

来自分类Dev

大数据文件中的r droplevel

来自分类Dev

在Java代码中嵌入数据文件

来自分类Dev

处理数据文件中的多列

来自分类Dev

在C ++中读取“大”数据文件

来自分类Dev

在python中解析csv数据文件

来自分类Dev

如何删除Linux中数据文件中少于两列的行?

来自分类Dev

如何通过与另一个数据文件进行比较来提取数据文件中的某些行?(合并中)

来自分类Dev

合并数据文件

来自分类Dev

如何删除数据文件夹中的文件?

来自分类Dev

读取具有可变大小的行的数据文件

来自分类Dev

读取大型矩阵数据文件的特定行

来自分类Dev

读取具有可变大小的行的数据文件

来自分类Dev

堆叠来自多个数据文件的行

来自分类Dev

如何将数据文件的某些行读入R

来自分类Dev

读取大型矩阵数据文件的特定行

来自分类Dev

堆叠来自多个数据文件的行