w3resource

Pandas: Create a series with a PeriodIndex which represents all the calendar month periods in 2029 and 2031

Pandas Time Series: Exercise-29 with Solution

Write a Pandas program create a series with a PeriodIndex which represents all the calendar month periods in 2029 and 2031. Also print the values for all periods in 2030.

Note: PeriodIndex is an immutable ndarray holding ordinal values indicating regular periods in time such as particular years, quarters, months, etc.

Sample Solution:

Python Code :

import pandas as pd
import numpy as np
pi = pd.Series(np.random.randn(36), 
               pd.period_range('1/1/2029', 
                               '12/31/2031', freq='M'))
print("PeriodIndex which represents all the calendar month periods in 2029 and 2030:")
print(pi)
print("\nValues for all periods in 2030:")
print(pi['2030'])

Sample Output:

PeriodIndex which represents all the calendar month periods in 2029 and 2030:
2029-01    0.382450
2029-02   -1.077418
2029-03    0.131711
2029-04    1.044379
2029-05   -0.101383
2029-06    0.149212
2029-07    1.241014
2029-08    0.242632
2029-09   -0.252832
2029-10   -2.267629
2029-11    0.716542
2029-12   -1.397595
2030-01    0.005339
2030-02    0.454597
2030-03    1.140378
2030-04    1.024139
2030-05    1.744527
2030-06    0.827034
2030-07   -0.610342
2030-08    0.533601
2030-09   -2.200672
2030-10   -0.373814
2030-11   -1.366233
2030-12    0.173628
2031-01    0.691684
2031-02   -0.583149
2031-03    1.076706
2031-04   -3.059091
2031-05   -1.584180
2031-06    0.209410
2031-07   -0.984389
2031-08   -0.134217
2031-09    1.541736
2031-10    0.125816
2031-11   -0.066537
2031-12   -1.076096
Freq: M, dtype: float64

Values for all periods in 2030:
2030-01    0.005339
2030-02    0.454597
2030-03    1.140378
2030-04    1.024139
2030-05    1.744527
2030-06    0.827034
2030-07   -0.610342
2030-08    0.533601
2030-09   -2.200672
2030-10   -0.373814
2030-11   -1.366233
2030-12    0.173628
Freq: M, dtype: float64

Python Code Editor:

Follow us on Facebook and Twitter for latest update.