Finding the average of a list
For Python 3.8+, use statistics.fmean
for numerical stability with floats. (Fast.)
For Python 3.4+, use statistics.mean
for numerical stability with floats. (Slower.)
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
import statistics
statistics.mean(xs) # = 20.11111111111111
For older versions of Python 3, use
sum(xs) / len(xs)
For Python 2, convert len
to a float to get float division:
sum(xs) / float(len(xs))
Calculating average of list from certain point in list?
Suppose you want to round off the list from an index (Here 3)
mylist = [2, 8, 6, 7, 3, 2, 1]
def round_list(lst, index):
avg = [sum(lst[int(index):])/(len(lst)-index)]
new_lst = (lst[:int(index)]) + avg
return new_lst
new_list = round_list(mylist, 3)
print(new_list)
output : [2, 8, 6, 3.25]
Calculate average of a list of list of list of numbers
Use numpy's mean method. Numpy is very efficient and speed optimized library.
import numpy as np
AllProcessTimes = np.array([ [[1,2,3], [1,2,3], [1,2,3]],
[[1,2,3], [1,2,3], [1,2,3]],
[[1,2,3], [1,2,3], [1,2,3]],
[[1,2,3], [1,2,3], [1,2,3]],
[[2,4,6], [3,6,9], [4,8,12]] ])
AverageProcessTimes = np.mean(AllProcessTimes, axis=0)
How to find the average of the list elements within a dictionary?
You can use statistics.mean
to compute the mean, and max
with a custom key to get the key with a max mean:
sweets = {'cadbury': [180,90], 'candy': [190], 'milk chocolate': [150, 160], 'dark chocolate': [100], 'white chocolate': [180],
'ice cream': [122]}
from statistics import mean
max(sweets, key=lambda x: mean(sweets[x]))
Output: 'candy'
Finding the average of a list in python
Problem & Solution
The main problem with your code is that after reading your file and parsing the output, newvar
is a list of strings:
['0', '1', '2', '3', '4', '5']
Since sum
will not handle strings - and even if it could, you wouldn't get your desired output - you need to convert the strings to integers. This can be done using a simple list comprehension:
newvar = [int(s) for s in newvar]
You can then use sum
as normal:
sum(newvar) / len(newvar)
Which has the output:
2
Improvements
Here are some general improvements to your original code:
Use the context manager statement
with
to open your files. That way, you can be sure your files are always closed.Rather than using a slice to filter out alphanumeric lines, you can use a 'filter' in the list comprehension above to skip over them.
Here is the modified code:
with open('stats.txt', 'r') as file:
nums = [int(n) for n in file.read().splitlines() if n.isdigit()]
avg = sum(nums) / len(nums)
print(avg)
List of tuples and mean calculation
A pandas approach:
import pandas as pd
tuples = [(120, 'x'), (1120, 'y'), (1330, 'x'), (0, 't'), (1, 'x'), (0, 'd'), (2435, 'x')]
df = pd.DataFrame(tuples)
df[0][df[0]!=0].mean() #1001.2
Careful timing would be needed to see if this is any better than what you are currently doing. The actual mean calculation should be faster, but the gain could well be negated by the cost of conversion.
Finding average value in list of dictionaries based on another unique value
You need to group weights by index. defaultdict from the built-in collections module is useful here.
from collections import defaultdict
total = defaultdict(int)
cnts = defaultdict(int)
for d in values:
# add weights
total[d['index']] += d['weight']
# count indexes
cnts[d['index']] += 1
# find the mean
[{'index': k, 'mean weight': total[k]/cnts[k]} for k in total]
# [{'index': 0, 'mean weight': 0.5}, {'index': 1, 'mean weight': 0.5}]
Related Topics
Change Parent Shell's Environment from a Subprocess
Serving a Request from Gunicorn
Pandas Get Topmost N Records Within Each Group
What Do *Args and **Kwargs Mean
Accessing Pandas Column Using Squared Brackets VS Using a Dot (Like an Attribute)
What Exactly Does the .Join() Method Do
Iterate an Iterator by Chunks (Of N) in Python
How to Get Multiline Input from the User
Python - Pip Install Trouble Shooting - Permissionerror: [Winerror 5] Access Is Denied
No Module Named 'Virtualenvwrapper'
How to Make a Discontinuous Axis in Matplotlib
Using Pandas to Pd.Read_Excel() for Multiple Worksheets of the Same Workbook
How to Convert an Xml File to Nice Pandas Dataframe
How to See the Entire Http Request That's Being Sent by My Python Application
How to Use String.Replace() in Python 3.X
How Does Swapping of Members in Tuples (A,B)=(B,A) Work Internally