Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average Pandas Dataframe by Date

I have the following dataframe a list of dates

                       debt 
date                               
2017-11-17 16:00:00    77     
2017-11-17 17:00:00    73     
2017-11-17 18:00:00    74     
2017-11-17 19:00:00    73     
2017-11-17 20:00:00    74     
2017-11-17 21:00:00    71     

I am trying to group by the dates to find the average by dates without time

2017-11-17 74

I tried to do this df = df.groupby(df['date'].map(lambda x: x.day)) KeyError: 'date'

Is there any other way to do it please?

like image 814
J Ng Avatar asked Jan 30 '23 03:01

J Ng


1 Answers

If need dates in index use DatetimeIndex.date:

df = df.groupby(df.index.date).mean()
print (df)
                 debt
2017-11-17  73.666667

print (df.index)
Index([2017-11-17], dtype='object')

But better is for DatetimeIndex use DatetimeIndex.floor:

df = df.groupby(df.index.floor('d')).mean()
print (df)
                 debt
date                 
2017-11-17  73.666667

print (df.index)
DatetimeIndex(['2017-11-17'], dtype='datetime64[ns]', name='date', freq=None)
like image 178
jezrael Avatar answered Feb 02 '23 09:02

jezrael