Reputation: 368
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.
Upvotes: 5
Views: 16755
Reputation: 375865
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.
Upvotes: 5
Reputation: 7358
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]
Upvotes: 4