Arigion
Arigion

Reputation: 3558

Pandas 2.2: FutureWarning: Resampling with a PeriodIndex is deprecated

The pandas version 2.2 raises a warning when using this code:

import pandas as pd

df = pd.DataFrame.from_dict({"something": {pd.Period("2022", "Y-DEC"): 2.5}})
# FutureWarning: Resampling with a PeriodIndex is deprecated.
# Cast index to DatetimeIndex before resampling instead.
print(df.resample("M").ffill())

#          something
# 2022-01        2.5
# 2022-02        2.5
# 2022-03        2.5
# 2022-04        2.5
# 2022-05        2.5
# 2022-06        2.5
# 2022-07        2.5
# 2022-08        2.5
# 2022-09        2.5
# 2022-10        2.5
# 2022-11        2.5
# 2022-12        2.5

This does not work:

df.index = df.index.to_timestamp()
print(df.resample("M").ffill())

#             something
# 2022-01-31        2.5

I have PeriodIndex all over the place and I need to resample them a lot, filling gaps with ffill. How to do this with Pandas 2.2?

Upvotes: 1

Views: 900

Answers (1)

Oskar Hofmann
Oskar Hofmann

Reputation: 807

As far as I know, there is no way to this directly with pandas 2.2.0+.

df.index = df.index.to_timestamp()
print(df.resample("M").ffill())

#             something
# 2022-01-31        2.5

does work but when you use to_timestamp() you get a single DateTime (2022-01-31) so a monthly resampling does nothing here.

You have to create a range of DateTimes first, ideally via the date_range() function. Then you can resample.

Is there a reason why you want to use pandas 2.2.0+ ?

Upvotes: 0

Related Questions