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

在纯python中(无numpy等),如何找到二维列表中某些列的平均值?,python,arrays,csv,Python,Arrays,Csv,我目前使用CSV阅读器创建二维列表。首先,我去掉了标题信息,所以我的列表纯粹是数据。遗憾的是,有几列是文本(日期等),有些只是用于对照其他数据进行检查。我想做的是获取这些数据的某些列并获得平均值。我只需要忽略其他专栏。我有什么不同的方法可以做到这一点?我可能不在乎速度,我在读了csv后做了一次,我的csv文件可能有2000行左右,只有30列左右。这是假设所有行的长度都相等,如果不是,你可能需要添加一些try/except案例 lst = [] #This is the rows and colu

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

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

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)

是因为你没有安装numpy吗?这在numpy中是微不足道的。如果您担心容易安装numpy,我强烈推荐。它是免费的,安装numpy和许多其他有用的库,无需用户做很多决定,易于卸载,并且具有许可证。