5

I have a data frame indexed with a date (Python datetime object). How could I find the frequency as the number of months of data in the data frame?

I tried the attribute data_frame.index.freq, but it returns a none value. I also tried asfreq function using data_frame.asfreq('M',how={'start','end'} but it does not return the expected results. Please advise how I can get the expected results.

2 Answers 2

4

You want to convert you index of datetimes to a DatetimeIndex, the easiest way is to use to_datetime:

df.index = pd.to_datetime(df.index)

Now you can do timeseries/frame operations, like resample or TimeGrouper.

If your data has a consistent frequency, then this will be df.index.freq, if it doesn't (e.g. if some days are missing) then df.index.freq will be None.

2
  • Thanks your tip was useful. I think there is some missing data. Commented Apr 14, 2014 at 14:40
  • I find the idiom assert(isinstance(df.index.freq, pd.pandas._libs.tslibs.offsets.Day)) essential when moving around lots of data that is resampled. Commented Mar 26, 2022 at 15:41
4

You probably want to be use pandas Timestamp for your index instead of datetime to use 'freq'. See example below

import pandas as pd
dates = pd.date_range('2012-1-1','2012-2-1')
df = pd.DataFrame(index=dates)
print (df.index.freq)

yields,

<Day>

You can easily convert your dataframe like so,

df.index = [pd.Timestamp(d) for d in df.index]

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