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

2

5

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?

Dumpcart answered 28/11, 2012 at 23:29 Comment(0)
B
7

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
Bedesman answered 29/11, 2012 at 0:17 Comment(1)
@EvanBrown Think nothing of it! ;)Bedesman
B
4

You should specify (yes, explicitly) the data type, in this case, float (or int, whatever!):

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

Remember, you must provide a structure "array-like" for numpy.sum():

>>>import numpy as np
>>>
>>> mylist = [1, 5, 2]
>>> a = np.asarray(mylist)
>>> a.sum()
8

Alternatively:

>>> np.sum([1,5,2])
8
Bedesman answered 28/11, 2012 at 23:49 Comment(2)
I guess that is part of my question also. I have now isolated the column of numbers but they are not structured: 1.06500005722 1.27900004387 1.29099988937 1.64499998093 1.86100006104 1.35100007057 2.07699990273 1.54999995232 1.58100008965 It is just a vertical column of numbers. I have tried doing r=np.array(thelist) and r=np.asarray(thelist) etc. with no luck I just keep getting errors when I try to do the sum and mean.Dumpcart
you want to sum all the numbers?Bedesman

© 2022 - 2024 — McMap. All rights reserved.