Home > Enterprise >  How to calculate cumulative sum and average on file data in python
How to calculate cumulative sum and average on file data in python

Time:10-12

I have a below data in file

NAME,AGE,MARKS
A1,12,40
B1,13,54
C1,15,67
D1,11,41
E1,16,59
F1,10,60

If the data was in database table , I would have used Sum and Average function to get the cumulative sum and average

But How to get it with python is a bit challenging , As i am learner

Expected output :

 NAME,AGE,MARKS,CUM_SUM,AVG
    A1,12,40,40,40
    B1,13,54,94,47
    C1,15,67,161,53.66
    D1,11,41,202,50.5
    E1,16,59,261,43.5
    F1,10,60,321,45.85

CodePudding user response:

IIUC use:

df = pd.read_csv('file')


df['CUM_SUM'] = df['MARKS'].cumsum()

df['AVG'] = df['MARKS'].expanding().mean()
print (df)
  NAME  AGE  MARKS  CUM_SUM        AVG
0   A1   12     40       40  40.000000
1   B1   13     54       94  47.000000
2   C1   15     67      161  53.666667
3   D1   11     41      202  50.500000
4   E1   16     59      261  52.200000
5   F1   10     60      321  53.500000

Last use:

df.to_csv('file.csv', index=False)

Or:

out = df.to_string(index=False)

CodePudding user response:

Try using pandas cumsum on df['MARKS'], I guess it will look like:

df['CUMSUM'] = df['MARKS'].cumsum()
  • Related