2012-11-27 59 views
0

使用Python NumPy的計算矩陣的列的總和時:的test2.csv「內置方法總和」怪異消息打印總和

import numpy 
from StringIO import StringIO 

fileName = 'test2.csv' 
myFile = open(fileName,'r') 
print "Reading data from '%s' ..." % fileName 
data = myFile.read() 
myFile.close() 

data = numpy.genfromtxt(StringIO(data), delimiter=',', usecols=(0,1,2)) 
print "Calculating ..." 

print data[:,2] 
sumA1 = data[:,2].sum 
print "shape =", data.shape 
print "sumA1 =", str(sumA1) 
print "ok" 

然後內容:

12,13,14,17 
1,2,3,4 
12,13,14,17 
1,2,3,4 
12,13,14,17 
1,2,3,4 
12,13,14,17 
1,2,3,4 
12,13,14,17 

我得到這個輸出

Reading data from 'test2.csv' ... 
Calculating ... 
[ 14. 3. 14. 3. 14. 3. 14. 3. 14.] 
shape = (9, 3) 
sumA1 = <built-in method sum of numpy.ndarray object at 0x00FD8EF8> 
ok 

爲什麼我不能得到「sumA1 = 82」 insted的那個怪異的消息的?我究竟做錯了什麼?

非常感謝您提前。

回答

5

您必須撥打sum功能。這一個

sumA1 = data[:,2].sum 

:只需更換這一段代碼

sumA1 = data[:,2].sum() 
+1

非常感謝你。它也適用於: sumA1 = numpy.sum(data [:,2]) – SonOfabox