简体   繁体   中英

Pandas resampling: how to generate offset rules string from TimeDelta

Is there a way to generate the offset rule string accepted by DataFrame.resample (eg 'T', '3W', '2D', etc ) starting from a TimeDelta or another object representing a time frequency?

I know that DataFrame.resample can accept a TimeDelta, but I like to know how to generate the string programmatically without having to invent my own function.

td = pd.TimeDelta('3min')
str(td)

Output

'0 days 00:03:00'

Actually I would like to obtain an offset rule string: eg '3T'

The docs explain that str(t)

Returns a string in the form [D day[s], ][H]H:MM:SS[.UUUUUU], where D is negative for negative t.

You wanted to know if timedelta offers support for output like '3W' without having a user function (trivially) format its numeric output into such a format. No, it does not offer such support.

You may find to_perioddelta() helpful when you write such a function.

In case someone else needs to write their own function like myself, here is the code:

def timedelta_to_string(timedelta):
    """
    Converts a pandas.Timedelta to a string rappresentation
    compatible with pandas.Timedelta constructor format
    """
    c = timedelta.components
    format = ''
    if c.days != 0:
        format += '%dD' % c.days
    if c.hours > 0:
        format += '%dh' % c.hours
    if c.minutes > 0:
        format += '%dm' % c.minutes
    if c.seconds > 0:
        format += '%ds' % c.seconds
    if c.milliseconds > 0:
        format += '%dms' % c.milliseconds
    if c.microseconds > 0:
        format += '%dus' % c.microseconds
    if c.nanoseconds > 0:
        format += '%dns' % c.nanoseconds
return format

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM