How to round a Pandas `DatetimeIndex`?

前端 未结 4 1320
栀梦
栀梦 2021-01-11 10:04

I have a pandas.DatetimeIndex, e.g.:

pd.date_range(\'2012-1-1 02:03:04.000\',periods=3,freq=\'1ms\')
>>> [2012-01-01 02:03:04, ..., 201         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-11 10:42

    There is little point in changing the index itself - since you can just generate using date_range with the desired frequency parameter as in your question.

    I assume what you are trying to do is change the frequency of a Time Series that contains data, in which case you can use resample (documentation). For example if you have the following time series:

    dt_index = pd.date_range('2012-1-1 00:00.001',periods=3, freq='1ms')
    ts = pd.Series(randn(3), index=dt_index)
    
    
    2012-01-01 00:00:00           0.594618
    2012-01-01 00:00:00.001000    0.874552
    2012-01-01 00:00:00.002000   -0.700076
    Freq: L
    

    Then you can change the frequency to seconds using resample, specifying how you want to aggregate the values (mean, sum etc.):

    ts.resample('S', how='sum')
    
    2012-01-01 00:00:00    0.594618
    2012-01-01 00:00:01    0.174475
    Freq: S
    

提交回复
热议问题