Dates4


PYT-DS SAISOFT

DATA SCIENCE WITH PYTHON

Pandas Periods


In [ ]:
import pandas as pd
from pandas import Series, DataFrame, Period, Timestamp
import numpy as np

In [ ]:
p = Period(2007, freq='A-DEC')  # an interval from Jan 1 to Dec 31, 2007
p

In [ ]:
p + 5

In [ ]:
p - 2

In [ ]:
p - Period(2000, freq='A-DEC')

In [ ]:
rng_years = pd.period_range('1/1/2000', '1/1/2018', freq='Y')

In [ ]:
rng_years

In [ ]:
rng_months = pd.period_range('1/1/2000', '1/1/2018', freq='M')

In [ ]:
rng_months

In [ ]:
type(rng_months)

In [ ]:
s = Series(np.random.randn(len(rng_years)), index=rng_years)
s

In [ ]:
s.index

In [ ]:
rng_years

In [ ]:
rng_years.asfreq('M', how='start')

In [ ]:
rng_years.asfreq('M', how='end')

In [ ]:
rng_years.asfreq('D', how='end')

In [ ]:
rng_months.asfreq('D', how='end')

In [ ]:
fiscal_year = Period('2007', freq='A-JUN')

In [ ]:
fiscal_year.asfreq('M', 'start')

In [ ]:
fiscal_year.asfreq('M', 'end')

In [ ]:
fiscal_year.asfreq('D', 'start')

In [ ]:
fiscal_year.asfreq('D', 'end')

Quarterly Period Frequencies


In [ ]:
p = Period('2018Q4', freq='Q-JAN')

In [ ]:
p

In [ ]:
p.asfreq('D', 'start')

In [ ]:
p.asfreq('D', 'end')

In [ ]:
p.asfreq('Y', 'start')

In [ ]:
p.asfreq('M', 'start')

In [ ]:
p.asfreq('M', 'start') + 3

In [ ]:
p.asfreq('Q-JAN', 'start')

In [ ]:
p.asfreq('Q-JAN', 'end')

In [ ]:
p.asfreq('Q', 'end')

Timestamps to Periods (and Back)


In [ ]:
rng = pd.date_range('1/1/2018', periods=6, freq='M')

In [ ]:
rng

In [ ]:
ts = Series(np.random.randn(6), index=rng)

In [ ]:
ts

In [ ]:
pts = ts.to_period()

In [ ]:
pts

In [ ]:
rng = pd.date_range('1/28/2018', periods=10, freq='D')
ts2 = Series(np.random.randn(len(rng)), index=rng)

In [ ]:
ts2

In [ ]:
ts2.to_period('M')

In [ ]:
pts

In [ ]:
pts.to_timestamp(how='end')

In [ ]:
pts.to_timestamp(how='start')

In [ ]:
pts2 = ts2.to_period('M')

In [ ]:
pts2

In [ ]:
pts2.to_timestamp(how='end')

In [ ]:
ts

In [ ]:
%matplotlib inline
ts.plot(kind="bar")

In [ ]:
ts.plot(kind="line")

LAB CHALLENGE:

Using documentation (of course!) create a horizontal bar graph from the same data (ts).