Description
Pandas version checks
-
I have checked that this issue has not already been reported.
-
I have confirmed this bug exists on the latest version of pandas.
-
I have confirmed this bug exists on the main branch of pandas.
Reproducible Example
import pandas as pd
datetime_index = pd.date_range("2020-01-01", freq="MS", periods=10)
period_index = datetime_index.to_period()
final_index = period_index.to_timestamp(freq=datetime_index.freq)
assert all(final_index == datetime_index)
Issue Description
When converting a pd.PeriodIndex
to a pd.DatetimeIndex
via pd.PeriodIndex.to_timestamp
we may wish to specify the desired frequency via the freq
keyword argument. But this is not possible if we want the index to be at the start of each period, e.g. if we use freq="MS"
. We receive the following error:
Traceback (most recent call last):
File "/scratch6.py", line 4, in <module>
final_index = period_index.to_timestamp(freq=datetime_index.freq)
File "/home/paul/.local/lib/python3.8/site-packages/pandas/core/indexes/period.py", line 177, in to_timestamp
arr = self._data.to_timestamp(freq, how)
File "/home/paul/.local/lib/python3.8/site-packages/pandas/core/arrays/period.py", line 506, in to_timestamp
base = freq._period_dtype_code
AttributeError: 'pandas._libs.tslibs.offsets.MonthBegin' object has no attribute '_period_dtype_code'
Expected Behavior
I think the code should behave similarly to the example below:
import pandas as pd
datetime_index = pd.date_range("2020-01-01", freq="M", periods=10)
period_index = datetime_index.to_period()
final_index = period_index.to_timestamp(freq=datetime_index.freq)
assert all(final_index == datetime_index)
which produces no error.
Installed Versions
INSTALLED VERSIONS
commit : e8093ba
python : 3.8.12.final.0
python-bits : 64
OS : Linux
OS-release : 5.15.0-46-generic
Version : #49~20.04.1-Ubuntu SMP Thu Aug 4 19:15:44 UTC 2022
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_GB.UTF-8
LOCALE : en_GB.UTF-8
pandas : 1.4.3
numpy : 1.21.6
pytz : 2021.3
dateutil : 2.8.2
setuptools : 63.4.1
pip : 22.2.2
Cython : 0.29.32
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.8.0
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.1.1
IPython : 7.32.0
pandas_datareader: None
bs4 : 4.11.1
bottleneck : None
brotli : 1.0.9
fastparquet : 0.8.1
fsspec : 2022.3.0
gcsfs : None
markupsafe : 2.1.1
matplotlib : None
numba : 0.55.1
numexpr : None
odfpy : None
openpyxl : 3.0.9
pandas_gbq : None
pyarrow : 9.0.0
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.8.1
snappy : None
sqlalchemy : 1.4.36
tables : None
tabulate : None
xarray : 2022.3.0
xlrd : 2.0.1
xlwt : None
zstandard : None