import pandas as pd import numpy as np np.random.seed(0) # create an array of 5 dates starting at '2015-02-24', one per minute rng = pd.date_range('2015-02-24', periods=5, freq='T') df = pd.DataFrame({ 'Date': rng, 'Val': np.random.randn(len(rng)) }) print (df) # Output: # Date Val # 0 2015-02-24 00:00:00 1.764052 # 1 2015-02-24 00:01:00 0.400157 # 2 2015-02-24 00:02:00 0.978738 # 3 2015-02-24 00:03:00 2.240893 # 4 2015-02-24 00:04:00 1.867558 # create an array of 5 dates starting at '2015-02-24', one per day rng = pd.date_range('2015-02-24', periods=5, freq='D') df = pd.DataFrame({ 'Date': rng, 'Val' : np.random.randn(len(rng))}) print (df) # Output: # Date Val # 0 2015-02-24 -0.977278 # 1 2015-02-25 0.950088 # 2 2015-02-26 -0.151357 # 3 2015-02-27 -0.103219 # 4 2015-02-28 0.410599 # create an array of 5 dates starting at '2015-02-24', one every 3 years rng = pd.date_range('2015-02-24', periods=5, freq='3A') df = pd.DataFrame({ 'Date': rng, 'Val' : np.random.randn(len(rng))}) print (df) # Output: # Date Val # 0 2015-12-31 0.144044 # 1 2018-12-31 1.454274 # 2 2021-12-31 0.761038 # 3 2024-12-31 0.121675 # 4 2027-12-31 0.443863
具有DatetimeIndex以下内容的DataFrame:
import pandas as pd import numpy as np np.random.seed(0) rng = pd.date_range('2015-02-24', periods=5, freq='T') df = pd.DataFrame({ 'Val' : np.random.randn(len(rng)) }, index=rng) print (df) # Output: # Val # 2015-02-24 00:00:00 1.764052 # 2015-02-24 00:01:00 0.400157 # 2015-02-24 00:02:00 0.978738 # 2015-02-24 00:03:00 2.240893 # 2015-02-24 00:04:00 1.867558
Offset-aliases为参数freq在date_range:
Alias Description B business day frequency C custom business day frequency (experimental) D calendar day frequency W weekly frequency M month end frequency BM business month end frequency CBM custom business month end frequency MS month start frequency 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 business year end frequency AS year start frequency BAS 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