pandas resample timeframe code example

Example 1: how i resamplae a datetime column in python

>>> d = dict({'price': [10, 11, 9, 13, 14, 18, 17, 19],
...           'volume': [50, 60, 40, 100, 50, 100, 40, 50]})
>>> df = pd.DataFrame(d)
>>> df['week_starting'] = pd.date_range('01/01/2018',
...                                     periods=8,
...                                     freq='W')
>>> df
   price  volume week_starting
0     10      50    2018-01-07
1     11      60    2018-01-14
2      9      40    2018-01-21
3     13     100    2018-01-28
4     14      50    2018-02-04
5     18     100    2018-02-11
6     17      40    2018-02-18
7     19      50    2018-02-25
# try below code when you want resample on datetime column to other all columns in dataframe
>>> df.resample('M', on='week_starting').mean() 
               price  volume
week_starting
2018-01-31     10.75    62.5
2018-02-28     17.00    60.0

Example 2: resample 5 minutes on date

df['timestamps'] = pd.to_datetime(df['timestamps'])
df.set_index('timestamps', inplace=True)

>>> df.resample('5T', how=ohlc_dict)

                         high     close      open       low    volume
timestamps                                                           
2016-08-09 12:35:00  536.7849  536.7849  536.7841  536.6141  0.656000
2016-08-09 12:40:00  536.6749  534.8416  536.6749  534.1801  2.277200
2016-08-09 12:45:00  538.5999  537.7289  534.8131  534.2303  2.971872
2016-08-09 12:50:00  539.2199  539.2199  537.9829  537.9829  1.115219

Example 3: pandas resample documentation

B         business day frequency
C         custom business day frequency (experimental)
D         calendar day frequency
W         weekly frequency
M         month end frequency
SM        semi-month end frequency (15th and end of month)
BM        business month end frequency
CBM       custom business month end frequency
MS        month start frequency
SMS       semi-month start frequency (1st and 15th)
BMS       business month start frequency
CBMS      custom business month start frequency
Q         quarter end frequency
BQ        business quarter endfrequency
QS        quarter start frequency
BQS       business quarter start frequency
A         year end frequency
BA, BY    business year end frequency
AS, YS    year start frequency
BAS, BYS  business year start frequency
BH        business hour frequency
H         hourly frequency
T, min    minutely frequency
S         secondly frequency
L, ms     milliseconds
U, us     microseconds
N         nanoseconds