piRSquared piRSquared - 1 month ago 9
Python Question

Set pandas.tseries.index.DatetimeIndex.freq with inferred_freq

consider the

DatetimeIndex
tidx


tidx = pd.to_datetime(['2016-07-29', '2016-08-31', '2016-09-30'])
print(tidx.freq)
print(tidx.inferred_freq)
print(tidx)

None
BM
DatetimeIndex(['2016-07-29', '2016-08-31', '2016-09-30'], \
dtype='datetime64[ns]', freq=None)


I want the
freq
attribute to assume the
inferred_freq
attribute... so I

tidx.freq = tidx.inferred_freq
print(tidx)



--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-24-b49b104fda04> in <module>()
1 tidx.freq = tidx.inferred_freq
----> 2 print(tidx)

C:\Users\ssmith\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\base.pyc in __str__(self)
45 if compat.PY3:
46 return self.__unicode__()
---> 47 return self.__bytes__()
48
49 def __bytes__(self):

C:\Users\ssmith\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\base.pyc in __bytes__(self)
57
58 encoding = get_option("display.encoding")
---> 59 return self.__unicode__().encode(encoding, 'replace')
60
61 def __repr__(self):

C:\Users\ssmith\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\indexes\base.pyc in __unicode__(self)
581 klass = self.__class__.__name__
582 data = self._format_data()
--> 583 attrs = self._format_attrs()
584 space = self._format_space()
585

C:\Users\ssmith\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\tseries\base.pyc in _format_attrs(self)
485 for attrib in self._attributes:
486 if attrib == 'freq':
--> 487 freq = self.freqstr
488 if freq is not None:
489 freq = "'%s'" % freq

C:\Users\ssmith\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\tseries\base.pyc in freqstr(self)
223 if self.freq is None:
224 return None
--> 225 return self.freq.freqstr
226
227 @cache_readonly

AttributeError: 'str' object has no attribute 'freqstr'






question

What is the appropriate way to have my index assume it's inferred_freq?

Answer

It's unclear why the docs state you can set the freq attribute but then it doesn't persist but if you reconstruct the datetimeindex again but pass a freq param then it works:

In [56]:
tidx = pd.DatetimeIndex(tidx.values, freq = tidx.inferred_freq)
tidx

Out[56]:
DatetimeIndex(['2016-07-29', '2016-08-31', '2016-09-30'], dtype='datetime64[ns]', freq='BM')
Comments