Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: DatetimeIndex.set_freq() #61094

Open
1 of 3 tasks
rwijtvliet opened this issue Mar 10, 2025 · 0 comments
Open
1 of 3 tasks

ENH: DatetimeIndex.set_freq() #61094

rwijtvliet opened this issue Mar 10, 2025 · 0 comments
Labels
Enhancement Needs Triage Issue that has not been reviewed by a pandas team member

Comments

@rwijtvliet
Copy link

rwijtvliet commented Mar 10, 2025

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

@rwijtvliet rwijtvliet added Enhancement Needs Triage Issue that has not been reviewed by a pandas team member labels Mar 10, 2025
@rwijtvliet rwijtvliet changed the title ENH: DatetimeIndex.with_freq() ENH: DatetimeIndex.set_freq() Mar 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Enhancement Needs Triage Issue that has not been reviewed by a pandas team member
Projects
None yet
Development

No branches or pull requests

1 participant