Skip to content

ENH: DatetimeIndex.set_freq() #61094

@rwijtvliet

Description

@rwijtvliet

Feature Type

  • Adding new functionality to pandas

  • Changing existing functionality in pandas

  • Removing existing functionality in pandas

Problem Description

I can set/change the name of a DatetimeIndex with .rename(). But I cannot set/change its frequency in the same manner.

Feature Description

To rename a DatetimeIndex, I can do this inplace with idx.name = 'foo'. Or I can get a new object with idx2 = idx.rename('foo').

I can set or change the frequency inplace with idx.freq = 'QS-APR', but an analogous method for setting or changing the frequency does not exist.

This proposal is to add the method DatetimeIndex.set_freq

Considering the method name: with_freq() or set_freq() would both work. I would not use as_freq() to avoid confusion with the existing methods Series.as_freq() and DataFrame.as_freq() which have a different functionality (i.e., change the index length).

The method body would be something like

def set_freq(self, freq, *, inplace: bool = False) -> Self | None:
    if inplace: 
        self.freq = freq
    else:
        idx = self.copy()
        idx.freq = freq
        return idx        

I'm happy to create a PR for this if devs think this is a worthwhile addition

Alternative Solutions

I can keep on using

idx2 = idx.copy()
idx2.freq = freq

but that cannot be used in list comprehensions or lambda expressions and is not chainable, and looks more clunky.

If I need something chainable, the best I think I can do is

idx2 = idx.to_frame().asfreq(freq).index

though that undeservedly raises an Exception if the frequencies are equivalent (e.g. QS-FEB and QS-MAY).

Additional Context

See also #61086

Metadata

Metadata

Assignees

Labels

EnhancementNeeds TriageIssue that has not been reviewed by a pandas team member

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions