0

I want to calculate the average temperature per day within an specific time frame, for example average temperature on the date = 2021-03-11 between time = 14:23:00 and 16:53:00. I tried with a pivot_table the following:

in_range_df = pd.pivot_table(df, values=['Air_temp'],
                 index=['Date','Time'],
                  aggfunc={'Air_temp':np.mean})

The dataframe looks like this:

1

But how can I specify the time range now? Any help is appreciated.

eshirvana
  • 23,227
  • 3
  • 22
  • 38
  • 3
    Please don't post images of code, data, or Tracebacks. [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) – wwii Dec 06 '21 at 15:02
  • 2
    Are the date and time columns strings or datetime64 datatypes? ... `df.dtypes`. – wwii Dec 06 '21 at 15:06
  • Do any of these answer your question? [Selecting Data between Specific hours in a pandas dataframe](https://stackoverflow.com/questions/19179214/selecting-data-between-specific-hours-in-a-pandas-dataframe), [Pandas how to filter DataFrame on time period](https://stackoverflow.com/questions/49172824/pandas-how-to-filter-dataframe-on-time-period), [Filter by hour in Pandas](https://stackoverflow.com/questions/20036953/filter-by-hour-in-pandas)?? – wwii Dec 06 '21 at 15:24

2 Answers2

3

Usually you can use between :

df[df["Datum"].between('2021-03-11 14:23:00',
                       '2021-03-11 16:53:00',)]["Air_temp"].mean()
eshirvana
  • 23,227
  • 3
  • 22
  • 38
0

First you should convert Datum column to datetime type:

df['Datum'] = pd.to_datetime(df['Datum'])

Then you can use df.loc like this:

t1 = '2021-03-11 14:23:00'
t2 = '2021-03-11 16:53:00'

df.loc[(df['Datum'] > t1) & (df['Datum'] < t2)]['Air_tmp'].mean()