Build a Pandas pd.tseries.offsets from string

451 Views Asked by At

Pandas provides a method for DataFrame and Timeseries named resample.

see http://pandas.pydata.org/pandas-docs/dev/timeseries.html

and http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.resample.html

this method have a parameter named rule

so we can do (to resample with 2 hours sampling period) :

ts2 = ts.resample('2H', how='mean')

I'm looking for a way to convert this '2H' string parameter to a Pandas pd.tseries.offsets

(because

In [10]: ts2.index.freq
Out[10]: <2 * Hours>

and

In [11]: type(ts2.index.freq)
Out[11]: pandas.tseries.offsets.Hour

I was looking for a method like:

pd.tseries.offsets.from_string('2H')

but it doesn't seems to exists.

Any help is welcome.

1

There are 1 best solutions below

1
On BEST ANSWER
In [13]: from pandas.tseries.frequencies import to_offset

In [14]: to_offset('2H')
Out[14]: <2 * Hours>

though you dont' really need to do this, e.g. resample will call this to convert string inputs. And you can simply call it with the constructed frequency, e.g. df.resample(pd.offsets.Hour(2)....) as well.