« Pandas date & time « Pandas
Generate Periodindex of fixed frequency.
Options
start Start of the generating period.
end End of the generating period.
periods number of periods to generate.
Note that two of the above ( start, end , periods ) options has to be used.
freq Frequency is 'D' by default. We can specify to others.
Examples
import pandas as pd
pd.period_range(start='4/1/2020', end='12/31/2020',freq='M')
Output , Here frequency is Months
PeriodIndex(['2020-04', '2020-05', '2020-06', '2020-07', '2020-08', '2020-09',
'2020-10', '2020-11', '2020-12'],
dtype='period[M]', freq='M')
Q : Quarter end frequency
pd.period_range(start='4/1/2020', end='12/31/2020',freq='Q')
Output
PeriodIndex(['2020Q2', '2020Q3', '2020Q4'], dtype='period[Q-DEC]', freq='Q-DEC')
Weekly frequency
pd.period_range(start='4/1/2020', end='4/30/2020',freq='W')
Output
PeriodIndex(['2020-03-30/2020-04-05', '2020-04-06/2020-04-12',
'2020-04-13/2020-04-19', '2020-04-20/2020-04-26',
'2020-04-27/2020-05-03'],
dtype='period[W-SUN]', freq='W-SUN')
We used start and end options in above code. Similarly we can use other options.
Business Day
pd.period_range(start='4/1/2020', end='4/30/2020',freq='B')
Output
PeriodIndex(['2020-04-01', '2020-04-02', '2020-04-03', '2020-04-06',
'2020-04-07', '2020-04-08', '2020-04-09', '2020-04-10',
'2020-04-13', '2020-04-14', '2020-04-15', '2020-04-16',
'2020-04-17', '2020-04-20', '2020-04-21', '2020-04-22',
'2020-04-23', '2020-04-24', '2020-04-27', '2020-04-28',
'2020-04-29', '2020-04-30'],
dtype='period[B]', freq='B')
periods
We can specify integer values like periods=3, this is optional.
import pandas as pd
pd.period_range(start='4/20/2020',periods=3,freq='M')
Output
PeriodIndex(['2020-04', '2020-05', '2020-06'], dtype='period[M]', freq='M')
name
We can give name of to the resulting DataFrame.
« Pandas date & time
to_datetime()
date_range()
strftime()
← Subscribe to our YouTube Channel here