0

使用 Python NumPy 计算矩阵列的总和:

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"

然后内容test2.csv

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”这个奇怪的信息?我究竟做错了什么?

非常感谢您提前。

4

1 回答 1

6

您必须调用该sum函数。只需替换这段代码:

sumA1 = data[:,2].sum

有了这个:

sumA1 = data[:,2].sum()
于 2012-11-27T11:22:25.320 回答