简体   繁体   中英

Resample Pandas Dataframe based on a DatetimeIndex variable

I have a dataframe with a Date index:

           Symbol  Shares  Price  Commission
Date                                        
2017-12-06    BNP       0      0        10.0
2018-10-09    BNP       0      0        10.0

and a seperate DatetimeIndex variable:

DatetimeIndex(['2014-02-14', '2014-02-15', '2014-02-16', '2014-02-17',
               ...
               '2020-04-11', '2020-04-12'],
              dtype='datetime64[ns]', length=2250, freq='D')

I'm trying to resample the dataframe based on that variable. Any way to do that? I know about pandas.DataFrame.resample but it seems like it can only be used for "regular" resampling (ie daily, weekly, etc.)

I'm brand new to python, migrating from MATLAB.

Thank you!

It depends on how you want to do it, please check: http://pandas-docs.github.io/pandas-docs-travis/user_guide/timeseries.html

However, Series and DataFrame can directly also support the time component as data itself.

I bring just some example:

rng = pd.date_range('1/1/2012', periods=100, freq='S')
ts = pd.Series(np.random.randint(0, 500, len(rng)), index=rng)
ts.resample('W-MON')

idx = pd.date_range('2018-01-01', periods=5, freq='H')
ts = pd.Series(range(len(idx)), index=idx)
Output: 
2018-01-01 00:00:00    0
2018-01-01 01:00:00    1
2018-01-01 02:00:00    2
2018-01-01 03:00:00    3
2018-01-01 04:00:00    4

pd.Series(range(3), index=pd.date_range('2000', freq='D', periods=3))
Output: 
2000-01-01    0
2000-01-02    1
2000-01-03    2

pd.Series(pd.period_range('1/1/2011', freq='M', periods=3))
Output: 
0   2000-01-01
1   2000-01-02
2   2000-01-03

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM