Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cumulative average in python

I'm working with csv files.

I'd like a to create a continuously updated average of a sequence. ex;

I'd like to output the average of each individual value of a list

list; [a, b, c, d, e, f]
formula:

(a)/1= ?

(a+b)/2=?

(a+b+c)/3=?

(a+b+c+d)/4=?

(a+b+c+d+e)/5=?

(a+b+c+d+e+f)/6=?

To demonstrate:

if i have a list; [1, 4, 7, 4, 19]

my output should be; [1, 2.5, 4, 4, 7]

explained;

(1)/1=1

(1+4)/2=2.5

(1+4+7)/3=4

(1+4+7+4)/4=4

(1+4+7+4+19)/5=7

As far as my python file it is a simple code:

import matplotlib.pyplot as plt

import pandas as pd

df = pd.read_csv('somecsvfile.csv')

x = [] #has to be a list of 1 to however many rows are in the "numbers" column, will be a simple [1, 2, 3, 4, 5] etc...

#x will be used to divide the numbers selected in y to give us z

y = df[numbers]

z = #new dataframe derived from the continuous average of y

plt.plot(x, z)

plt.show()

If numpy is needed that is no problem.

like image 296
Wocky Bocky Avatar asked Sep 26 '26 01:09

Wocky Bocky


1 Answers

pandas.DataFrame.expanding is what you need.

Using it you can just call df.expanding().mean() to get the result you want:

mean = df.expanding().mean()

print(mean)

Out[10]: 
0   1.0
1   2.5
2   4.0
3   4.0
4   7.0

If you want to do it just in one column, use pandas.Series.expanding.

Just use the column instead of df:

df['column_name'].expanding().mean()
like image 86
Augusto Quaglia Avatar answered Sep 27 '26 13:09

Augusto Quaglia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!