2015-09-06 101 views
-2

我目前使用CSV阅读器创建一个二维列表。首先,我删除标题信息,因此我的列表纯粹是数据。可悲的是,几列是文本(日期等),有些仅用于检查其他数据。我想要做的是采取这些数据的某些列并获得平均值。我只需要忽略其他列。有什么不同的方式可以做到这一点?我可能不关心速度,我在阅读csv后只做了一次,而我的CSV文件可能有2000行左右,只有30左右的列。在纯python(没有numpy等)中,如何找到二维列表中某些列的平均值?

+0

是否因为您没有安装numpy?这在numpy中是微不足道的。 – 2015-09-06 02:43:50

+0

如果您担心轻松安装numpy,我强烈推荐[Anaconda](http://continuum.io/downloads)。它是免费的,安装numpy和一系列其他有用的库,没有很多用户决定,很容易卸载,并有许可[许可证](http://docs.continuum.io/anaconda/eula)。 – Ben

回答

0

这是假设所有的行长度相等的,如果他们没有,你可能要在

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 

希望这有助于;我无法测试此代码,因为我在手机上。

0

试试这个:

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) 
相关问题