Using Python NumPy to calculate the sum of the column of a matrix:
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"
Then contents of 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
I get this output
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
Why can’t I get “sumA1 = 82” insted of that weird message? What am I doing wrong?
Thank you very much in advance.
You have to make a call of the
sumfunction. Just replace this piece of code:with this one: