shlomi
shlomi

Reputation: 549

How to calculate mean in python?

I have a list that I want to calculate the average(mean?) of the values for her. When I do this:

import numpy as np #in the beginning of the code

goodPix = ['96.7958', '97.4333', '96.7938', '96.2792', '97.2292']
PixAvg = np.mean(goodPix)

I'm getting this error code:

ret = um.add.reduce(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims)

TypeError: cannot perform reduce with flexible type

I tried to find some help but didn't find something that was helpful

Thank you all.

Upvotes: 9

Views: 10513

Answers (5)

handle
handle

Reputation: 6319

If you're not using numpy, the obvious way to calculate the arithmetic mean of a list of values is to divide the sum of all elements by the number of elements, which is easily achieved using the two built-ins sum() and len(), e.g.:

>>> l = [1,3]
>>> sum(l)/len(l)
2.0

In case the list elements are strings, one way to convert them is with a list comprehension:

>>> s = ['1','3']
>>> l = [float(e) for e in s]
>>> l
[1.0, 3.0]

For an integer result, use the // operator ("floored quotient of x and y") or convert with int().

For many other solutions, also see Calculating arithmetic mean (one type of average) in Python

Upvotes: 0

Chetan Sharma
Chetan Sharma

Reputation: 1442

There is a statistics library if you are using python >= 3.4

https://docs.python.org/3/library/statistics.html

You may use it's mean method like this. Let's say you have a list of numbers of which you want to find mean:-

list = [11, 13, 12, 15, 17]
import statistics as s
s.mean(list)

It has other methods too like stdev, variance, mode etc.

Upvotes: 4

Vlad Bezden
Vlad Bezden

Reputation: 89577

Using list comprehension

>>> np.mean([float(n) for n in goodPix])
96.906260000000003

Upvotes: 0

alko
alko

Reputation: 48317

Convert you list from strings to np.float:

>>> gp = np.array(goodPix, np.float)
>>> np.mean(gp)
96.906260000000003

Upvotes: 10

usethedeathstar
usethedeathstar

Reputation: 2309

The things are still strings instead of floats. Try the following:

goodPix = ['96.7958', '97.4333', '96.7938', '96.2792', '97.2292']
gp2 = []
for i in goodPix:
    gp2.append(float(i))
numpy.mean(gp2)

Upvotes: 2

Related Questions