1

I was going through the Periods in pandas and couldnt find any particular use for it and i dont think it is any different from the date, for instance

  1. To get the datetime, I use

    datetime(2012,1,1)

  2. To get a range of dates, I use

    pd.date_range('1/1/2000', periods=10)

My question is, why would one use Period? According to the definition

Periods represent timespans, like days, months, quarters, or years.

p = pd.Period(2007, freq='A-DEC')

In this case, the Period object represents the full timespan from January 1, 2007, to December 31, 2007, inclusive. But if i go by definition, i should be able to groupby using the Period as i holds a range of timespan, but when i try to groupby, i am getting error

_period=pd.Period('2000',freq='M')
x = pd.date_range('1/1/2000', periods=14)
_result=pd.Series(range(len(x)),index=x)
_result.groupby(_period)

can anyone please help me understand when should i use Period and what and all problems can i solve using it

1 Answer 1

1

For aggregate by periods convert DatetimeIndex to PeriodIndex here by DatetimeIndex.to_period:

print (_result.index.to_period('m'))
PeriodIndex(['2000-01', '2000-01', '2000-01', '2000-01', '2000-01', '2000-01',
             '2000-01', '2000-01', '2000-01', '2000-01', '2000-01', '2000-01',
             '2000-01', '2000-01'],
            dtype='period[M]', freq='M')

print (_result.groupby(_result.index.to_period('m')).sum())
2000-01    91
Freq: M, dtype: int64
4
  • can you help me on, when to use Period or what is the key difference between Period and Datetime Sep 18, 2020 at 12:00
  • 1
    @LijinDurairaj - It is used for [Regular intervals of time are represented by Period objects in pandas while sequences of Period objects are collected in a PeriodIndex,](https://pandas.pydata.org/docs/user_guide/timeseries.html#time-span-representation). It means practically if need processing e.g. data by months and years is possible use df.years with df.moths or dt.to_periods('m') for working with months periods. It shuld be altrnative to pd.Grouper(freq='m').
    – jezrael
    Sep 18, 2020 at 12:06
  • What is means practically is possible seen here
    – jezrael
    Sep 18, 2020 at 12:06
  • i have gone through the link which you have provided, now my question is what is the difference between Period and Datetime, when Period can add year, month, day and time like the Datetime, thanks for your help Sep 18, 2020 at 17:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.