How to calculate mean for a selected range?(pandas)

Viewed 67

I have a dataframe like

Date           Volume

9/23/2019      50
9/24/2019      234
9/25/2019      23124
9/26/2019      23412
9/27/2019      21213
9/30/2019      23241
10/1/2019      231323
10/2/2019      2312
10/3/2019      23213
10/4/2019      421020
10/7/2019      3212
10/8/2019      23122



import pandas as pd
i = input('enter credentials')
df = pd.read_csv('sample.csv')

I want to calculate the mean on two conditions:

if the input i is m, then it should calculate the mean of the month and display the result by month, if the input i is w, it should calculate the mean of the week and display the result by week.

There can be more dataframes, a week has 5 days and a month has 20 days in this case.

1 Answers

You havent showed us the output but by the description, you can try passing the input into this function (extendable):

First convert the date to an actual datetime col:

df['Date'] = pd.to_datetime(df['Date'],format='%m/%d/%Y')

Then :

def myinp(i,dataframe,datecol):
    freq_d = {'m':'m','w':'W'}
    return dataframe.groupby(dataframe[datecol]
          .dt.strftime(f"%{freq_d.get(i)}").rename(i)).mean()

print("By m: \n",myinp('m',df,'Date'))
print("---------------------------")
print("By w: \n",myinp('w',df,'Date'))

By m: 
            Volume
m                
09   15212.333333
10  117367.000000
---------------------------
By w: 
       Volume
w           
38   13606.6
39  140221.8
40   13167.0
Related