Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding Sum of a Column in a List Getting "TypeError: cannot perform reduce with flexible type"

So I am new to python and have searched for this answer but most responses are over my head. I have a list like this:

right point point 1.76999998093
right fear fear 1.62700009346
right sit sit 1.46899986267
right chord chord 1.47900009155
right speed speeed 1.71300005913
right system system 1.69799995422
right hard hard 1.4470000267
right excite excite 2.93799996376
right govern govern 1.85800004005
right record record 1.62400007248

I am trying to split the list into columns and find the mean/sum/std dev of the numbers. So basically i am just trying to get the last into an array form I can use np.mean, np.sum, etc with. The data is in a file called 'right' Here is what I have so far:

right=open('right.txt').readlines()
for line in right: 
    l=line.split()
    righttime=l[3]
    print righttime

rightsum=np.sum(righttime)
rightmean=np.mean(righttime)

Then I get this error: "TypeError: cannot perform reduce with flexible type" I have tried it tons of ways and keep getting errors. This is another way I tried that seemed promising:

def TimeSum(data):
    for line in data: 
        l=line.split()
        righttime=l[3]
        print righttime
    return righttime

rightsum=np.sum(TimeSum(right))

But I had the same error. Does anyone know how to do this?

like image 258
Evan Brown Avatar asked Nov 28 '12 23:11

Evan Brown


1 Answers

Generate a list and sum the elements:

import numpy as np

right = open('right.txt').readlines()
mylist = []

for line in right:
    l = line.split()  
    mylist.append(float(l[3])) # add to list "mylist"   

rightsum = np.sum(mylist)
print rightsum

Or, alternatively

mylist = [float(line.split()[3]) for line in right] # generate numbers list
print np.sum(mylist) # sum numbers
like image 171
felipsmartins Avatar answered Oct 12 '22 00:10

felipsmartins