2010-06-26 181 views
23

任何人都知道我該如何計算這些列的平均值(在Linux上)?如何計算列的平均值

sda    2.91 20.44 6.13 2.95 217.53 186.67 44.55  0.84 92.97 
sda    0.00  0.00 2.00 0.00 80.00  0.00 40.00  0.22 110.00 
sda    0.00  0.00 2.00 0.00 144.00  0.00 72.00  0.71 100.00 
sda    0.00 64.00 0.00 1.00  0.00  8.00  8.00  2.63 10.00 
sda    0.00  1.84 0.31 1.38 22.09 104.29 74.91  3.39 2291.82 
sda    0.00  0.00 0.00 0.00  0.00  0.00  0.00  0.00 0.00 

例如:平均值(第2列)

+1

http://unix.stackexchange.com/questions/13731/is-there-a-way-to -get-the-min-max-median-and-average-of-numbers-of-numbers-in – 2015-11-21 11:14:04

回答

52

awk中:

awk '{ total += $2 } END { print total/NR }' yourFile.whatever 

閱讀爲:

  • 對於每一行,將第2列添加到變量「total」。
  • 在文件末尾,打印「總數」除以記錄數。
+0

...或者你可以隨時使用AWK :) :) +1 – OscarRyz 2010-06-26 02:28:40

+0

非常感謝...它很簡單,而且效果非常好! – Alucard 2010-06-26 03:19:56

+0

@Porges:如何訪問特定的時間間隔:比方說在第二列中,我想找到元素2到6的意思? – 2016-09-26 17:21:24

1

您可以用Python的是,可在Linux中。

如果是來自一個文件,看看這個question,只需使用float。

例如:

#mean.py 
def main(): 
    with open("mean.txt", 'r') as f: 
     data = [map(float, line.split()) for line in f] 

    columnTwo = [] 
    for row in data: 
     columnTwo.append(row[1]) 

    print sum(columnTwo,0.0)/len(columnTwo) 



if __name__=="__main__": 
    main() 

打印14.38

我只是包括在mean.txt文件中的數據,而不是行頭: 「SDA」

+1

我的第一個想法可能是Python以及......但是使這個列表在這裏可能過於低效,因爲你只需要總和和行數。 (另外,爲了它的樂趣:'開放(「mean.txt」,'r')爲f:n,t = map(sum,zip(*((1,float(line。split()[1]))for line in f))); print t/n') – 2010-06-26 02:43:52

0

David Zaslavsky爲它的樂趣:

with open("mean.txt", 'r') as f: 
    n,t = map(sum, zip(*((1, float(line.split()[1])) for line in f))) 
print t/n 
0

Simple-r將計算平均值,其具有以下行:

r -k2 mean file.txt 

第二列。它也可以做更復雜的統計分析,因爲它使用R environment進行所有的統計分析。

3

Perl的溶液:

perl -lane '$total += $F[1]; END{print $total/$.}' file 

-a autosplits行成@F陣列,其索引從0開始
$.是行號

如果您的字段由逗號分隔代替的空格:

perl -F, -lane '$total += $F[1]; END{print $total/$.}' file 

要打印的意思所有列的值,分配給總計數組@t:

perl -lane 'for $c (0..$#F){$t[$c] += $F[$c]}; END{for $c (0..$#t){print $t[$c]/$.}}' 

輸出:

0 
0.485 
14.38 
1.74 
0.888333333333333 
77.27 
49.8266666666667 
39.91 
1.29833333333333 
434.131666666667