forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 3
/
timeseries.rst
2449 lines (1633 loc) · 80.2 KB
/
timeseries.rst
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
.. _timeseries:
{{ header }}
********************************
Time Series / Date functionality
********************************
pandas contains extensive capabilities and features for working with time series data for all domains.
Using the NumPy ``datetime64`` and ``timedelta64`` dtypes, pandas has consolidated a large number of
features from other Python libraries like ``scikits.timeseries`` as well as created
a tremendous amount of new functionality for manipulating time series data.
For example, pandas supports:
Parsing time series information from various sources and formats
.. ipython:: python
import datetime
dti = pd.to_datetime(['1/1/2018', np.datetime64('2018-01-01'),
datetime.datetime(2018, 1, 1)])
dti
Generate sequences of fixed-frequency dates and time spans
.. ipython:: python
dti = pd.date_range('2018-01-01', periods=3, freq='H')
dti
Manipulating and converting date times with timezone information
.. ipython:: python
dti = dti.tz_localize('UTC')
dti
dti.tz_convert('US/Pacific')
Resampling or converting a time series to a particular frequency
.. ipython:: python
idx = pd.date_range('2018-01-01', periods=5, freq='H')
ts = pd.Series(range(len(idx)), index=idx)
ts
ts.resample('2H').mean()
Performing date and time arithmetic with absolute or relative time increments
.. ipython:: python
friday = pd.Timestamp('2018-01-05')
friday.day_name()
# Add 1 day
saturday = friday + pd.Timedelta('1 day')
saturday.day_name()
# Add 1 business day (Friday --> Monday)
monday = friday + pd.offsets.BDay()
monday.day_name()
pandas provides a relatively compact and self-contained set of tools for
performing the above tasks and more.
.. _timeseries.overview:
Overview
--------
pandas captures 4 general time related concepts:
#. Date times: A specific date and time with timezone support. Similar to ``datetime.datetime`` from the standard library.
#. Time deltas: An absolute time duration. Similar to ``datetime.timedelta`` from the standard library.
#. Time spans: A span of time defined by a point in time and its associated frequency.
#. Date offsets: A relative time duration that respects calendar arithmetic. Similar to ``dateutil.relativedelta.relativedelta`` from the ``dateutil`` package.
===================== ================= =================== ============================================ ========================================
Concept Scalar Class Array Class pandas Data Type Primary Creation Method
===================== ================= =================== ============================================ ========================================
Date times ``Timestamp`` ``DatetimeIndex`` ``datetime64[ns]`` or ``datetime64[ns, tz]`` ``to_datetime`` or ``date_range``
Time deltas ``Timedelta`` ``TimedeltaIndex`` ``timedelta64[ns]`` ``to_timedelta`` or ``timedelta_range``
Time spans ``Period`` ``PeriodIndex`` ``period[freq]`` ``Period`` or ``period_range``
Date offsets ``DateOffset`` ``None`` ``None`` ``DateOffset``
===================== ================= =================== ============================================ ========================================
For time series data, it's conventional to represent the time component in the index of a :class:`Series` or :class:`DataFrame`
so manipulations can be performed with respect to the time element.
.. ipython:: python
pd.Series(range(3), index=pd.date_range('2000', freq='D', periods=3))
However, :class:`Series` and :class:`DataFrame` can directly also support the time component as data itself.
.. ipython:: python
pd.Series(pd.date_range('2000', freq='D', periods=3))
:class:`Series` and :class:`DataFrame` have extended data type support and functionality for ``datetime``, ``timedelta``
and ``Period`` data when passed into those constructors. ``DateOffset``
data however will be stored as ``object`` data.
.. ipython:: python
pd.Series(pd.period_range('1/1/2011', freq='M', periods=3))
pd.Series([pd.DateOffset(1), pd.DateOffset(2)])
pd.Series(pd.date_range('1/1/2011', freq='M', periods=3))
Lastly, pandas represents null date times, time deltas, and time spans as ``NaT`` which
is useful for representing missing or null date like values and behaves similar
as ``np.nan`` does for float data.
.. ipython:: python
pd.Timestamp(pd.NaT)
pd.Timedelta(pd.NaT)
pd.Period(pd.NaT)
# Equality acts as np.nan would
pd.NaT == pd.NaT
.. _timeseries.representation:
Timestamps vs. Time Spans
-------------------------
Timestamped data is the most basic type of time series data that associates
values with points in time. For pandas objects it means using the points in
time.
.. ipython:: python
pd.Timestamp(datetime.datetime(2012, 5, 1))
pd.Timestamp('2012-05-01')
pd.Timestamp(2012, 5, 1)
However, in many cases it is more natural to associate things like change
variables with a time span instead. The span represented by ``Period`` can be
specified explicitly, or inferred from datetime string format.
For example:
.. ipython:: python
pd.Period('2011-01')
pd.Period('2012-05', freq='D')
:class:`Timestamp` and :class:`Period` can serve as an index. Lists of
``Timestamp`` and ``Period`` are automatically coerced to :class:`DatetimeIndex`
and :class:`PeriodIndex` respectively.
.. ipython:: python
dates = [pd.Timestamp('2012-05-01'),
pd.Timestamp('2012-05-02'),
pd.Timestamp('2012-05-03')]
ts = pd.Series(np.random.randn(3), dates)
type(ts.index)
ts.index
ts
periods = [pd.Period('2012-01'), pd.Period('2012-02'), pd.Period('2012-03')]
ts = pd.Series(np.random.randn(3), periods)
type(ts.index)
ts.index
ts
pandas allows you to capture both representations and
convert between them. Under the hood, pandas represents timestamps using
instances of ``Timestamp`` and sequences of timestamps using instances of
``DatetimeIndex``. For regular time spans, pandas uses ``Period`` objects for
scalar values and ``PeriodIndex`` for sequences of spans. Better support for
irregular intervals with arbitrary start and end points are forth-coming in
future releases.
.. _timeseries.converting:
Converting to Timestamps
------------------------
To convert a :class:`Series` or list-like object of date-like objects e.g. strings,
epochs, or a mixture, you can use the ``to_datetime`` function. When passed
a ``Series``, this returns a ``Series`` (with the same index), while a list-like
is converted to a ``DatetimeIndex``:
.. ipython:: python
pd.to_datetime(pd.Series(['Jul 31, 2009', '2010-01-10', None]))
pd.to_datetime(['2005/11/23', '2010.12.31'])
If you use dates which start with the day first (i.e. European style),
you can pass the ``dayfirst`` flag:
.. ipython:: python
pd.to_datetime(['04-01-2012 10:00'], dayfirst=True)
pd.to_datetime(['14-01-2012', '01-14-2012'], dayfirst=True)
.. warning::
You see in the above example that ``dayfirst`` isn't strict, so if a date
can't be parsed with the day being first it will be parsed as if
``dayfirst`` were False.
If you pass a single string to ``to_datetime``, it returns a single ``Timestamp``.
``Timestamp`` can also accept string input, but it doesn't accept string parsing
options like ``dayfirst`` or ``format``, so use ``to_datetime`` if these are required.
.. ipython:: python
pd.to_datetime('2010/11/12')
pd.Timestamp('2010/11/12')
You can also use the ``DatetimeIndex`` constructor directly:
.. ipython:: python
pd.DatetimeIndex(['2018-01-01', '2018-01-03', '2018-01-05'])
The string 'infer' can be passed in order to set the frequency of the index as the
inferred frequency upon creation:
.. ipython:: python
pd.DatetimeIndex(['2018-01-01', '2018-01-03', '2018-01-05'], freq='infer')
Providing a Format Argument
~~~~~~~~~~~~~~~~~~~~~~~~~~~
In addition to the required datetime string, a ``format`` argument can be passed to ensure specific parsing.
This could also potentially speed up the conversion considerably.
.. ipython:: python
pd.to_datetime('2010/11/12', format='%Y/%m/%d')
pd.to_datetime('12-11-2010 00:00', format='%d-%m-%Y %H:%M')
For more information on the choices available when specifying the ``format``
option, see the Python `datetime documentation`_.
.. _datetime documentation: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
Assembling Datetime from Multiple DataFrame Columns
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 0.18.1
You can also pass a ``DataFrame`` of integer or string columns to assemble into a ``Series`` of ``Timestamps``.
.. ipython:: python
df = pd.DataFrame({'year': [2015, 2016],
'month': [2, 3],
'day': [4, 5],
'hour': [2, 3]})
pd.to_datetime(df)
You can pass only the columns that you need to assemble.
.. ipython:: python
pd.to_datetime(df[['year', 'month', 'day']])
``pd.to_datetime`` looks for standard designations of the datetime component in the column names, including:
* required: ``year``, ``month``, ``day``
* optional: ``hour``, ``minute``, ``second``, ``millisecond``, ``microsecond``, ``nanosecond``
Invalid Data
~~~~~~~~~~~~
The default behavior, ``errors='raise'``, is to raise when unparseable:
.. code-block:: ipython
In [2]: pd.to_datetime(['2009/07/31', 'asd'], errors='raise')
ValueError: Unknown string format
Pass ``errors='ignore'`` to return the original input when unparseable:
.. ipython:: python
pd.to_datetime(['2009/07/31', 'asd'], errors='ignore')
Pass ``errors='coerce'`` to convert unparseable data to ``NaT`` (not a time):
.. ipython:: python
pd.to_datetime(['2009/07/31', 'asd'], errors='coerce')
.. _timeseries.converting.epoch:
Epoch Timestamps
~~~~~~~~~~~~~~~~
pandas supports converting integer or float epoch times to ``Timestamp`` and
``DatetimeIndex``. The default unit is nanoseconds, since that is how ``Timestamp``
objects are stored internally. However, epochs are often stored in another ``unit``
which can be specified. These are computed from the starting point specified by the
``origin`` parameter.
.. ipython:: python
pd.to_datetime([1349720105, 1349806505, 1349892905,
1349979305, 1350065705], unit='s')
pd.to_datetime([1349720105100, 1349720105200, 1349720105300,
1349720105400, 1349720105500], unit='ms')
.. note::
Epoch times will be rounded to the nearest nanosecond.
.. warning::
Conversion of float epoch times can lead to inaccurate and unexpected results.
:ref:`Python floats <python:tut-fp-issues>` have about 15 digits precision in
decimal. Rounding during conversion from float to high precision ``Timestamp`` is
unavoidable. The only way to achieve exact precision is to use a fixed-width
types (e.g. an int64).
.. ipython:: python
pd.to_datetime([1490195805.433, 1490195805.433502912], unit='s')
pd.to_datetime(1490195805433502912, unit='ns')
.. seealso::
:ref:`timeseries.origin`
.. _timeseries.converting.epoch_inverse:
From Timestamps to Epoch
~~~~~~~~~~~~~~~~~~~~~~~~
To invert the operation from above, namely, to convert from a ``Timestamp`` to a 'unix' epoch:
.. ipython:: python
stamps = pd.date_range('2012-10-08 18:15:05', periods=4, freq='D')
stamps
We subtract the epoch (midnight at January 1, 1970 UTC) and then floor divide by the
"unit" (1 second).
.. ipython:: python
(stamps - pd.Timestamp("1970-01-01")) // pd.Timedelta('1s')
.. _timeseries.origin:
Using the ``origin`` Parameter
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 0.20.0
Using the ``origin`` parameter, one can specify an alternative starting point for creation
of a ``DatetimeIndex``. For example, to use 1960-01-01 as the starting date:
.. ipython:: python
pd.to_datetime([1, 2, 3], unit='D', origin=pd.Timestamp('1960-01-01'))
The default is set at ``origin='unix'``, which defaults to ``1970-01-01 00:00:00``.
Commonly called 'unix epoch' or POSIX time.
.. ipython:: python
pd.to_datetime([1, 2, 3], unit='D')
.. _timeseries.daterange:
Generating Ranges of Timestamps
-------------------------------
To generate an index with timestamps, you can use either the ``DatetimeIndex`` or
``Index`` constructor and pass in a list of datetime objects:
.. ipython:: python
dates = [datetime.datetime(2012, 5, 1),
datetime.datetime(2012, 5, 2),
datetime.datetime(2012, 5, 3)]
# Note the frequency information
index = pd.DatetimeIndex(dates)
index
# Automatically converted to DatetimeIndex
index = pd.Index(dates)
index
In practice this becomes very cumbersome because we often need a very long
index with a large number of timestamps. If we need timestamps on a regular
frequency, we can use the :func:`date_range` and :func:`bdate_range` functions
to create a ``DatetimeIndex``. The default frequency for ``date_range`` is a
**calendar day** while the default for ``bdate_range`` is a **business day**:
.. ipython:: python
start = datetime.datetime(2011, 1, 1)
end = datetime.datetime(2012, 1, 1)
index = pd.date_range(start, end)
index
index = pd.bdate_range(start, end)
index
Convenience functions like ``date_range`` and ``bdate_range`` can utilize a
variety of :ref:`frequency aliases <timeseries.offset_aliases>`:
.. ipython:: python
pd.date_range(start, periods=1000, freq='M')
pd.bdate_range(start, periods=250, freq='BQS')
``date_range`` and ``bdate_range`` make it easy to generate a range of dates
using various combinations of parameters like ``start``, ``end``, ``periods``,
and ``freq``. The start and end dates are strictly inclusive, so dates outside
of those specified will not be generated:
.. ipython:: python
pd.date_range(start, end, freq='BM')
pd.date_range(start, end, freq='W')
pd.bdate_range(end=end, periods=20)
pd.bdate_range(start=start, periods=20)
.. versionadded:: 0.23.0
Specifying ``start``, ``end``, and ``periods`` will generate a range of evenly spaced
dates from ``start`` to ``end`` inclusively, with ``periods`` number of elements in the
resulting ``DatetimeIndex``:
.. ipython:: python
pd.date_range('2018-01-01', '2018-01-05', periods=5)
pd.date_range('2018-01-01', '2018-01-05', periods=10)
.. _timeseries.custom-freq-ranges:
Custom Frequency Ranges
~~~~~~~~~~~~~~~~~~~~~~~
.. warning::
This functionality was originally exclusive to ``cdate_range``, which is
deprecated as of version 0.21.0 in favor of ``bdate_range``. Note that
``cdate_range`` only utilizes the ``weekmask`` and ``holidays`` parameters
when custom business day, 'C', is passed as the frequency string. Support has
been expanded with ``bdate_range`` to work with any custom frequency string.
.. versionadded:: 0.21.0
``bdate_range`` can also generate a range of custom frequency dates by using
the ``weekmask`` and ``holidays`` parameters. These parameters will only be
used if a custom frequency string is passed.
.. ipython:: python
weekmask = 'Mon Wed Fri'
holidays = [datetime.datetime(2011, 1, 5), datetime.datetime(2011, 3, 14)]
pd.bdate_range(start, end, freq='C', weekmask=weekmask, holidays=holidays)
pd.bdate_range(start, end, freq='CBMS', weekmask=weekmask)
.. seealso::
:ref:`timeseries.custombusinessdays`
.. _timeseries.timestamp-limits:
Timestamp Limitations
---------------------
Since pandas represents timestamps in nanosecond resolution, the time span that
can be represented using a 64-bit integer is limited to approximately 584 years:
.. ipython:: python
pd.Timestamp.min
pd.Timestamp.max
.. seealso::
:ref:`timeseries.oob`
.. _timeseries.datetimeindex:
Indexing
--------
One of the main uses for ``DatetimeIndex`` is as an index for pandas objects.
The ``DatetimeIndex`` class contains many time series related optimizations:
* A large range of dates for various offsets are pre-computed and cached
under the hood in order to make generating subsequent date ranges very fast
(just have to grab a slice).
* Fast shifting using the ``shift`` and ``tshift`` method on pandas objects.
* Unioning of overlapping ``DatetimeIndex`` objects with the same frequency is
very fast (important for fast data alignment).
* Quick access to date fields via properties such as ``year``, ``month``, etc.
* Regularization functions like ``snap`` and very fast ``asof`` logic.
``DatetimeIndex`` objects have all the basic functionality of regular ``Index``
objects, and a smorgasbord of advanced time series specific methods for easy
frequency processing.
.. seealso::
:ref:`Reindexing methods <basics.reindexing>`
.. note::
While pandas does not force you to have a sorted date index, some of these
methods may have unexpected or incorrect behavior if the dates are unsorted.
``DatetimeIndex`` can be used like a regular index and offers all of its
intelligent functionality like selection, slicing, etc.
.. ipython:: python
rng = pd.date_range(start, end, freq='BM')
ts = pd.Series(np.random.randn(len(rng)), index=rng)
ts.index
ts[:5].index
ts[::2].index
.. _timeseries.partialindexing:
Partial String Indexing
~~~~~~~~~~~~~~~~~~~~~~~
Dates and strings that parse to timestamps can be passed as indexing parameters:
.. ipython:: python
ts['1/31/2011']
ts[datetime.datetime(2011, 12, 25):]
ts['10/31/2011':'12/31/2011']
To provide convenience for accessing longer time series, you can also pass in
the year or year and month as strings:
.. ipython:: python
ts['2011']
ts['2011-6']
This type of slicing will work on a ``DataFrame`` with a ``DatetimeIndex`` as well. Since the
partial string selection is a form of label slicing, the endpoints **will be** included. This
would include matching times on an included date:
.. ipython:: python
dft = pd.DataFrame(np.random.randn(100000, 1), columns=['A'],
index=pd.date_range('20130101', periods=100000, freq='T'))
dft
dft['2013']
This starts on the very first time in the month, and includes the last date and
time for the month:
.. ipython:: python
dft['2013-1':'2013-2']
This specifies a stop time **that includes all of the times on the last day**:
.. ipython:: python
dft['2013-1':'2013-2-28']
This specifies an **exact** stop time (and is not the same as the above):
.. ipython:: python
dft['2013-1':'2013-2-28 00:00:00']
We are stopping on the included end-point as it is part of the index:
.. ipython:: python
dft['2013-1-15':'2013-1-15 12:30:00']
.. versionadded:: 0.18.0
``DatetimeIndex`` partial string indexing also works on a ``DataFrame`` with a ``MultiIndex``:
.. ipython:: python
dft2 = pd.DataFrame(np.random.randn(20, 1),
columns=['A'],
index=pd.MultiIndex.from_product(
[pd.date_range('20130101', periods=10, freq='12H'),
['a', 'b']]))
dft2
dft2.loc['2013-01-05']
idx = pd.IndexSlice
dft2 = dft2.swaplevel(0, 1).sort_index()
dft2.loc[idx[:, '2013-01-05'], :]
.. _timeseries.slice_vs_exact_match:
Slice vs. Exact Match
~~~~~~~~~~~~~~~~~~~~~
.. versionchanged:: 0.20.0
The same string used as an indexing parameter can be treated either as a slice or as an exact match depending on the resolution of the index. If the string is less accurate than the index, it will be treated as a slice, otherwise as an exact match.
Consider a ``Series`` object with a minute resolution index:
.. ipython:: python
series_minute = pd.Series([1, 2, 3],
pd.DatetimeIndex(['2011-12-31 23:59:00',
'2012-01-01 00:00:00',
'2012-01-01 00:02:00']))
series_minute.index.resolution
A timestamp string less accurate than a minute gives a ``Series`` object.
.. ipython:: python
series_minute['2011-12-31 23']
A timestamp string with minute resolution (or more accurate), gives a scalar instead, i.e. it is not casted to a slice.
.. ipython:: python
series_minute['2011-12-31 23:59']
series_minute['2011-12-31 23:59:00']
If index resolution is second, then the minute-accurate timestamp gives a
``Series``.
.. ipython:: python
series_second = pd.Series([1, 2, 3],
pd.DatetimeIndex(['2011-12-31 23:59:59',
'2012-01-01 00:00:00',
'2012-01-01 00:00:01']))
series_second.index.resolution
series_second['2011-12-31 23:59']
If the timestamp string is treated as a slice, it can be used to index ``DataFrame`` with ``[]`` as well.
.. ipython:: python
dft_minute = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]},
index=series_minute.index)
dft_minute['2011-12-31 23']
.. warning::
However, if the string is treated as an exact match, the selection in ``DataFrame``'s ``[]`` will be column-wise and not row-wise, see :ref:`Indexing Basics <indexing.basics>`. For example ``dft_minute['2011-12-31 23:59']`` will raise ``KeyError`` as ``'2012-12-31 23:59'`` has the same resolution as the index and there is no column with such name:
To *always* have unambiguous selection, whether the row is treated as a slice or a single selection, use ``.loc``.
.. ipython:: python
dft_minute.loc['2011-12-31 23:59']
Note also that ``DatetimeIndex`` resolution cannot be less precise than day.
.. ipython:: python
series_monthly = pd.Series([1, 2, 3],
pd.DatetimeIndex(['2011-12', '2012-01', '2012-02']))
series_monthly.index.resolution
series_monthly['2011-12'] # returns Series
Exact Indexing
~~~~~~~~~~~~~~
As discussed in previous section, indexing a ``DatetimeIndex`` with a partial string depends on the "accuracy" of the period, in other words how specific the interval is in relation to the resolution of the index. In contrast, indexing with ``Timestamp`` or ``datetime`` objects is exact, because the objects have exact meaning. These also follow the semantics of *including both endpoints*.
These ``Timestamp`` and ``datetime`` objects have exact ``hours, minutes,`` and ``seconds``, even though they were not explicitly specified (they are ``0``).
.. ipython:: python
dft[datetime.datetime(2013, 1, 1):datetime.datetime(2013, 2, 28)]
With no defaults.
.. ipython:: python
dft[datetime.datetime(2013, 1, 1, 10, 12, 0):
datetime.datetime(2013, 2, 28, 10, 12, 0)]
Truncating & Fancy Indexing
~~~~~~~~~~~~~~~~~~~~~~~~~~~
A :meth:`~DataFrame.truncate` convenience function is provided that is similar
to slicing. Note that ``truncate`` assumes a 0 value for any unspecified date
component in a ``DatetimeIndex`` in contrast to slicing which returns any
partially matching dates:
.. ipython:: python
rng2 = pd.date_range('2011-01-01', '2012-01-01', freq='W')
ts2 = pd.Series(np.random.randn(len(rng2)), index=rng2)
ts2.truncate(before='2011-11', after='2011-12')
ts2['2011-11':'2011-12']
Even complicated fancy indexing that breaks the ``DatetimeIndex`` frequency
regularity will result in a ``DatetimeIndex``, although frequency is lost:
.. ipython:: python
ts2[[0, 2, 6]].index
.. _timeseries.iterating-label:
Iterating through groups
------------------------
With the ``Resampler`` object in hand, iterating through the grouped data is very
natural and functions similarly to :py:func:`itertools.groupby`:
.. ipython:: python
small = pd.Series(
range(6),
index=pd.to_datetime(['2017-01-01T00:00:00',
'2017-01-01T00:30:00',
'2017-01-01T00:31:00',
'2017-01-01T01:00:00',
'2017-01-01T03:00:00',
'2017-01-01T03:05:00'])
)
resampled = small.resample('H')
for name, group in resampled:
print("Group: ", name)
print("-" * 27)
print(group, end="\n\n")
See :ref:`groupby.iterating-label` or :class:`Resampler.__iter__` for more.
.. _timeseries.components:
Time/Date Components
--------------------
There are several time/date properties that one can access from ``Timestamp`` or a collection of timestamps like a ``DatetimeIndex``.
.. csv-table::
:header: "Property", "Description"
:widths: 15, 65
year, "The year of the datetime"
month,"The month of the datetime"
day,"The days of the datetime"
hour,"The hour of the datetime"
minute,"The minutes of the datetime"
second,"The seconds of the datetime"
microsecond,"The microseconds of the datetime"
nanosecond,"The nanoseconds of the datetime"
date,"Returns datetime.date (does not contain timezone information)"
time,"Returns datetime.time (does not contain timezone information)"
timetz,"Returns datetime.time as local time with timezone information"
dayofyear,"The ordinal day of year"
weekofyear,"The week ordinal of the year"
week,"The week ordinal of the year"
dayofweek,"The number of the day of the week with Monday=0, Sunday=6"
weekday,"The number of the day of the week with Monday=0, Sunday=6"
weekday_name,"The name of the day in a week (ex: Friday)"
quarter,"Quarter of the date: Jan-Mar = 1, Apr-Jun = 2, etc."
days_in_month,"The number of days in the month of the datetime"
is_month_start,"Logical indicating if first day of month (defined by frequency)"
is_month_end,"Logical indicating if last day of month (defined by frequency)"
is_quarter_start,"Logical indicating if first day of quarter (defined by frequency)"
is_quarter_end,"Logical indicating if last day of quarter (defined by frequency)"
is_year_start,"Logical indicating if first day of year (defined by frequency)"
is_year_end,"Logical indicating if last day of year (defined by frequency)"
is_leap_year,"Logical indicating if the date belongs to a leap year"
Furthermore, if you have a ``Series`` with datetimelike values, then you can
access these properties via the ``.dt`` accessor, as detailed in the section
on :ref:`.dt accessors<basics.dt_accessors>`.
.. _timeseries.offsets:
DateOffset Objects
------------------
In the preceding examples, frequency strings (e.g. ``'D'``) were used to specify
a frequency that defined:
* how the date times in :class:`DatetimeIndex` were spaced when using :meth:`date_range`
* the frequency of a :class:`Period` or :class:`PeriodIndex`
These frequency strings map to a :class:`DateOffset` object and its subclasses. A :class:`DateOffset`
is similar to a :class:`Timedelta` that represents a duration of time but follows specific calendar duration rules.
For example, a :class:`Timedelta` day will always increment ``datetimes`` by 24 hours, while a :class:`DateOffset` day
will increment ``datetimes`` to the same time the next day whether a day represents 23, 24 or 25 hours due to daylight
savings time. However, all :class:`DateOffset` subclasses that are an hour or smaller
(``Hour``, ``Minute``, ``Second``, ``Milli``, ``Micro``, ``Nano``) behave like
:class:`Timedelta` and respect absolute time.
The basic :class:`DateOffset` acts similar to ``dateutil.relativedelta`` (`relativedelta documentation`_)
that shifts a date time by the corresponding calendar duration specified. The
arithmetic operator (``+``) or the ``apply`` method can be used to perform the shift.
.. ipython:: python
# This particular day contains a day light savings time transition
ts = pd.Timestamp('2016-10-30 00:00:00', tz='Europe/Helsinki')
# Respects absolute time
ts + pd.Timedelta(days=1)
# Respects calendar time
ts + pd.DateOffset(days=1)
friday = pd.Timestamp('2018-01-05')
friday.day_name()
# Add 2 business days (Friday --> Tuesday)
two_business_days = 2 * pd.offsets.BDay()
two_business_days.apply(friday)
friday + two_business_days
(friday + two_business_days).day_name()
Most ``DateOffsets`` have associated frequencies strings, or offset aliases, that can be passed
into ``freq`` keyword arguments. The available date offsets and associated frequency strings can be found below:
.. csv-table::
:header: "Date Offset", "Frequency String", "Description"
:widths: 15, 15, 65
:class:`~pandas.tseries.offsets.DateOffset`, None, "Generic offset class, defaults to 1 calendar day"
:class:`~pandas.tseries.offsets.BDay` or :class:`~pandas.tseries.offsets.BusinessDay`, ``'B'``,"business day (weekday)"
:class:`~pandas.tseries.offsets.CDay` or :class:`~pandas.tseries.offsets.CustomBusinessDay`, ``'C'``, "custom business day"
:class:`~pandas.tseries.offsets.Week`, ``'W'``, "one week, optionally anchored on a day of the week"
:class:`~pandas.tseries.offsets.WeekOfMonth`, ``'WOM'``, "the x-th day of the y-th week of each month"
:class:`~pandas.tseries.offsets.LastWeekOfMonth`, ``'LWOM'``, "the x-th day of the last week of each month"
:class:`~pandas.tseries.offsets.MonthEnd`, ``'M'``, "calendar month end"
:class:`~pandas.tseries.offsets.MonthBegin`, ``'MS'``, "calendar month begin"
:class:`~pandas.tseries.offsets.BMonthEnd` or :class:`~pandas.tseries.offsets.BusinessMonthEnd`, ``'BM'``, "business month end"
:class:`~pandas.tseries.offsets.BMonthBegin` or :class:`~pandas.tseries.offsets.BusinessMonthBegin`, ``'BMS'``, "business month begin"
:class:`~pandas.tseries.offsets.CBMonthEnd` or :class:`~pandas.tseries.offsets.CustomBusinessMonthEnd`, ``'CBM'``, "custom business month end"
:class:`~pandas.tseries.offsets.CBMonthBegin` or :class:`~pandas.tseries.offsets.CustomBusinessMonthBegin`, ``'CBMS'``, "custom business month begin"
:class:`~pandas.tseries.offsets.SemiMonthEnd`, ``'SM'``, "15th (or other day_of_month) and calendar month end"
:class:`~pandas.tseries.offsets.SemiMonthBegin`, ``'SMS'``, "15th (or other day_of_month) and calendar month begin"
:class:`~pandas.tseries.offsets.QuarterEnd`, ``'Q'``, "calendar quarter end"
:class:`~pandas.tseries.offsets.QuarterBegin`, ``'QS'``, "calendar quarter begin"
:class:`~pandas.tseries.offsets.BQuarterEnd`, ``'BQ``, "business quarter end"
:class:`~pandas.tseries.offsets.BQuarterBegin`, ``'BQS'``, "business quarter begin"
:class:`~pandas.tseries.offsets.FY5253Quarter`, ``'REQ'``, "retail (aka 52-53 week) quarter"
:class:`~pandas.tseries.offsets.YearEnd`, ``'A'``, "calendar year end"
:class:`~pandas.tseries.offsets.YearBegin`, ``'AS'`` or ``'BYS'``,"calendar year begin"
:class:`~pandas.tseries.offsets.BYearEnd`, ``'BA'``, "business year end"
:class:`~pandas.tseries.offsets.BYearBegin`, ``'BAS'``, "business year begin"
:class:`~pandas.tseries.offsets.FY5253`, ``'RE'``, "retail (aka 52-53 week) year"
:class:`~pandas.tseries.offsets.Easter`, None, "Easter holiday"
:class:`~pandas.tseries.offsets.BusinessHour`, ``'BH'``, "business hour"
:class:`~pandas.tseries.offsets.CustomBusinessHour`, ``'CBH'``, "custom business hour"
:class:`~pandas.tseries.offsets.Day`, ``'D'``, "one absolute day"
:class:`~pandas.tseries.offsets.Hour`, ``'H'``, "one hour"
:class:`~pandas.tseries.offsets.Minute`, ``'T'`` or ``'min'``,"one minute"
:class:`~pandas.tseries.offsets.Second`, ``'S'``, "one second"
:class:`~pandas.tseries.offsets.Milli`, ``'L'`` or ``'ms'``, "one millisecond"
:class:`~pandas.tseries.offsets.Micro`, ``'U'`` or ``'us'``, "one microsecond"
:class:`~pandas.tseries.offsets.Nano`, ``'N'``, "one nanosecond"
``DateOffsets`` additionally have :meth:`rollforward` and :meth:`rollback`
methods for moving a date forward or backward respectively to a valid offset
date relative to the offset. For example, business offsets will roll dates
that land on the weekends (Saturday and Sunday) forward to Monday since
business offsets operate on the weekdays.
.. ipython:: python
ts = pd.Timestamp('2018-01-06 00:00:00')
ts.day_name()
# BusinessHour's valid offset dates are Monday through Friday
offset = pd.offsets.BusinessHour(start='09:00')
# Bring the date to the closest offset date (Monday)
offset.rollforward(ts)
# Date is brought to the closest offset date first and then the hour is added
ts + offset
These operations preserve time (hour, minute, etc) information by default.
To reset time to midnight, use :meth:`normalize` before or after applying
the operation (depending on whether you want the time information included
in the operation).
.. ipython:: python
ts = pd.Timestamp('2014-01-01 09:00')
day = pd.offsets.Day()
day.apply(ts)
day.apply(ts).normalize()
ts = pd.Timestamp('2014-01-01 22:00')
hour = pd.offsets.Hour()
hour.apply(ts)
hour.apply(ts).normalize()
hour.apply(pd.Timestamp("2014-01-01 23:30")).normalize()
.. _relativedelta documentation: https://dateutil.readthedocs.io/en/stable/relativedelta.html
Parametric Offsets
~~~~~~~~~~~~~~~~~~
Some of the offsets can be "parameterized" when created to result in different
behaviors. For example, the ``Week`` offset for generating weekly data accepts a
``weekday`` parameter which results in the generated dates always lying on a
particular day of the week:
.. ipython:: python
d = datetime.datetime(2008, 8, 18, 9, 0)
d
d + pd.offsets.Week()
d + pd.offsets.Week(weekday=4)
(d + pd.offsets.Week(weekday=4)).weekday()
d - pd.offsets.Week()
The ``normalize`` option will be effective for addition and subtraction.
.. ipython:: python
d + pd.offsets.Week(normalize=True)
d - pd.offsets.Week(normalize=True)
Another example is parameterizing ``YearEnd`` with the specific ending month:
.. ipython:: python
d + pd.offsets.YearEnd()
d + pd.offsets.YearEnd(month=6)
.. _timeseries.offsetseries:
Using Offsets with ``Series`` / ``DatetimeIndex``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Offsets can be used with either a ``Series`` or ``DatetimeIndex`` to
apply the offset to each element.
.. ipython:: python
rng = pd.date_range('2012-01-01', '2012-01-03')
s = pd.Series(rng)
rng
rng + pd.DateOffset(months=2)
s + pd.DateOffset(months=2)
s - pd.DateOffset(months=2)
If the offset class maps directly to a ``Timedelta`` (``Day``, ``Hour``,
``Minute``, ``Second``, ``Micro``, ``Milli``, ``Nano``) it can be
used exactly like a ``Timedelta`` - see the
:ref:`Timedelta section<timedeltas.operations>` for more examples.
.. ipython:: python
s - pd.offsets.Day(2)
td = s - pd.Series(pd.date_range('2011-12-29', '2011-12-31'))
td
td + pd.offsets.Minute(15)
Note that some offsets (such as ``BQuarterEnd``) do not have a
vectorized implementation. They can still be used but may
calculate significantly slower and will show a ``PerformanceWarning``
.. ipython:: python
:okwarning: