BUG: Timestamp.to_period() fails for freq="MS" · Issue #38914 · pandas-dev/pandas (original) (raw)
- I have checked that this issue has not already been reported.
- I have confirmed this bug exists on the latest version of pandas.
- (optional) I have confirmed this bug exists on the master branch of pandas.
Note: Please read this guide detailing how to provide the necessary information for us to reproduce your bug.
Code Sample, a copy-pastable example
idx = pd.date_range(start='1/1/2018', end='12/1/2018', freq="MS") idx[-1].to_period()
Problem description
This results in the following exception:
AttributeError Traceback (most recent call last) pandas_libs\tslibs\period.pyx in pandas._libs.tslibs.period.freq_to_dtype_code()
AttributeError: 'pandas._libs.tslibs.offsets.MonthBegin' object has no attribute '_period_dtype_code'
The above exception was the direct cause of the following exception:
ValueError Traceback (most recent call last) in 1 idx = pd.date_range(start='1/1/2018', end='12/1/2018', freq="MS") ----> 2 idx[-1].to_period()
pandas_libs\tslibs\timestamps.pyx in pandas._libs.tslibs.timestamps._Timestamp.to_period()
pandas_libs\tslibs\period.pyx in pandas._libs.tslibs.period.Period.new()
pandas_libs\tslibs\period.pyx in pandas._libs.tslibs.period.freq_to_dtype_code()
ValueError: Invalid frequency: {0}
Timestamp.to_period()
does not work for freq="MS"
, other freq
values might also not work?
Expected Output
This can only be achieved by the following workaround:
idx = pd.date_range(start='1/1/2018 00:00:00', end='1/5/2018 00:01:00', freq="MS") cutoff = idx[-1] date = pd.DatetimeIndex([cutoff], freq=cutoff.freq) date.to_period()[0]
Period('2018-01', 'M')
Output of pd.show_versions()
INSTALLED VERSIONS
commit : b5958ee
python : 3.8.5.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.18362
machine : AMD64
processor : AMD64 Family 21 Model 112 Stepping 0, AuthenticAMD
byteorder : little
LC_ALL : None
LANG : None
LOCALE : English_United States.1252
pandas : 1.1.5
numpy : 1.19.4
pytz : 2020.4
dateutil : 2.8.1
pip : 20.2.4
setuptools : 50.3.1.post20201107
Cython : 0.29.21
pytest : 3.6.0
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.11.2
IPython : 7.19.0
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : 0.8.4
fastparquet : None
gcsfs : None
matplotlib : 3.3.3
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pytables : None
pyxlsb : None
s3fs : None
scipy : 1.5.4
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : 0.50.1