1

pd.period_range(start='2017-01-01', end='2017-01-01', freq='Q') gives me the following: PeriodIndex(['2017Q1'], dtype='period[Q-DEC]', freq='Q-DEC')

I would like to gain access to '2017Q1' to put it into a different column in the dataframe.

I have a date column with dates, e.g., 1/1/2017. I have other column where I'd like to put the string calculated by the period range. It seems like that would be an efficient way to update the column with the fiscal quarter. I can't seem to access it. It isn't subscriptable, and I can't get at it even when I assign it to a variable. Just wondering what I'm missing.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
wiseass
  • 543
  • 2
  • 5
  • 11

1 Answers1

2

pandas.PeriodIndex:

  • You were almost there. It just needed to be assigned to a column
import numpy as np
from datetime import timedelta, datetime
import pandas as pd


# list of dates - test data
first_date = datetime(2017, 1, 1)
last_date = datetime(2019, 9, 20)
x = 4
list_of_dates = [date for date in np.arange(first_date, last_date, timedelta(days=x)).astype(datetime)]


# create the dataframe
df = pd.DataFrame({'dates': list_of_dates})

     dates
2017-01-01
2017-01-05
2017-01-09
2017-01-13
2017-01-17

df['Quarters'] = pd.PeriodIndex(df.dates, freq='Q-DEC')

Output:

print(df.head())

     dates Quarters
2017-01-01   2017Q1
2017-01-05   2017Q1
2017-01-09   2017Q1
2017-01-13   2017Q1
2017-01-17   2017Q1

print(df.tail())

     dates Quarters
2019-08-31   2019Q3
2019-09-04   2019Q3
2019-09-08   2019Q3
2019-09-12   2019Q3
2019-09-16   2019Q3
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158