繁体   English   中英

在纯python(没有numpy等)中,如何找到二维列表中某些列的平均值?

[英]In pure python (no numpy, etc.) how can I find the mean of certain columns of a two dimensional list?

我目前使用 CSV 阅读器来创建一个二维列表。 首先,我去掉标题信息,所以我的列表纯粹是数据。 遗憾的是,有几列是文本(日期等),有些仅用于检查其他数据。 我想做的是取这些数据的某些列并获得平均值。 其他列我只需要忽略。 我有哪些不同的方法可以做到这一点? 我可能不关心速度,我在阅读了 csv 之后做了一次,我的 CSV 文件可能有 2000 行左右,只有 30 列左右。

这是假设所有行的长度相等,如果不是,您可能需要添加一些 try / except case

lst = [] #This is the rows and columns, assuming the rows contain the columns
column = 2 
temp = 0
for row in range (len(lst)):
    temp += lst [row][column]
mean = temp / len (lst)

为了测试元素是否是数字,在大多数情况下,我使用

try:
    float(element) # int may also work depending on your data
except ValueError:
    pass

希望这可以帮助; 我无法测试此代码,因为我正在使用手机。

尝试这个:

def avg_columns(list_name, *column_numbers):
    running_sum = 0
    for col in column_numbers:
        for row in range(len(list_name)):
            running_sum += list_name[row][col]
    return running_sum / (len(list_name)*len(column_numbers))

您将列表的名称和列的索引(从 0 开始)传递给它,它将返回这些列的平均值。

l = [
    [1,2,3],
    [1,2,3]
]
print(avg_columns(l, 0)) # returns 1.0, the avg of the first column (index 0)
print(avg_columns(l, 0, 2)) # returns 2.0, the avg of column indices 0 and 2 (first and third)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM