Q. Given a dataframe that stores the details of past 25 years' monthly sales. Some old data is however missing. Write a script to calculate average:

* Monthly sales across years
* Yearly sales

Make sure that missing values do not hamper the overall result.


Answer :-

import pandas as pd
import numpy as np
d1 = {' 2020' : [101,101,103,102,104,101,101,103,102,104,np.nan,101], '2019' : [ 101,101,103,102,104,101,101,103,102,104,65,101], \
'2018' : [90,40,50,90,65,np.nan,101,103,102,104,65,109], '2017' : [np.nan,80,60,85,np.nan,101,101,103,102,104,65,101], \
       '2016' : [np.nan,80,60,85,np.nan,101,201,103,100,104,65,101]}
df = pd. DataFrame (d1)
print (df)
print('Average Monthly sales across years', end = '  ')
for i in list(df):
    print(i, end = ' : ')
    print((df[i].sum())/12)

print()
print('Average Yearly sales : ')
sum = 0
for i in list(df):
    sum += df[i].sum()
print(sum/25)


Output :-


     2020  2019   2018   2017   2016
0   101.0   101   90.0    NaN    NaN
1   101.0   101   40.0   80.0   80.0
2   103.0   103   50.0   60.0   60.0
3   102.0   102   90.0   85.0   85.0
4   104.0   104   65.0    NaN    NaN
5   101.0   101    NaN  101.0  101.0
6   101.0   101  101.0  101.0  201.0
7   103.0   103  103.0  103.0  103.0
8   102.0   102  102.0  102.0  100.0
9   104.0   104  104.0  104.0  104.0
10    NaN    65   65.0   65.0   65.0
11  101.0   101  109.0  101.0  101.0
Average Monthly sales across years   2020 : 93.58333333333333
2019 : 99.0
2018 : 76.58333333333333
2017 : 75.16666666666667
2016 : 83.33333333333333

Average Yearly sales : 
205.28
>>>

1 Comments

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post