Skip to content

Commit

Permalink
BUG: PeriodIndex.__new__ with keyword mismatch (#55961)
Browse files Browse the repository at this point in the history
* BUG: PeriodIndex.__new__ with keyword mismatch

* GH refs
  • Loading branch information
jbrockmendel authored Nov 14, 2023
1 parent d7da0e6 commit e89d18c
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,7 @@ I/O

Period
^^^^^^
- Bug in :class:`PeriodIndex` construction when more than one of ``data``, ``ordinal`` and ``**fields`` are passed failing to raise ``ValueError`` (:issue:`55961`)
- Bug in :class:`Period` addition silently wrapping around instead of raising ``OverflowError`` (:issue:`55503`)
- Bug in casting from :class:`PeriodDtype` with ``astype`` to ``datetime64`` or :class:`DatetimeTZDtype` with non-nanosecond unit incorrectly returning with nanosecond unit (:issue:`55958`)
-
Expand Down
8 changes: 7 additions & 1 deletion pandas/core/indexes/period.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,11 @@ def __new__(

dtype = PeriodDtype(freq)
data = PeriodArray(data, dtype=dtype)
elif fields:
if data is not None:
raise ValueError("Cannot pass both data and fields")
raise ValueError("Cannot pass both ordinal and fields")

else:
freq = validate_dtype_freq(dtype, freq)

Expand All @@ -261,10 +266,11 @@ def __new__(
data = data.asfreq(freq)

if data is None and ordinal is not None:
# we strangely ignore `ordinal` if data is passed.
ordinal = np.asarray(ordinal, dtype=np.int64)
dtype = PeriodDtype(freq)
data = PeriodArray(ordinal, dtype=dtype)
elif data is not None and ordinal is not None:
raise ValueError("Cannot pass both data and ordinal")
else:
# don't pass copy here, since we copy later.
data = period_array(data=data, freq=freq)
Expand Down
16 changes: 16 additions & 0 deletions pandas/tests/indexes/period/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,22 @@


class TestPeriodIndex:
def test_keyword_mismatch(self):
# GH#55961 we should get exactly one of data/ordinals/**fields
per = Period("2016-01-01", "D")

err_msg1 = "Cannot pass both data and ordinal"
with pytest.raises(ValueError, match=err_msg1):
PeriodIndex(data=[per], ordinal=[per.ordinal], freq=per.freq)

err_msg2 = "Cannot pass both data and fields"
with pytest.raises(ValueError, match=err_msg2):
PeriodIndex(data=[per], year=[per.year], freq=per.freq)

err_msg3 = "Cannot pass both ordinal and fields"
with pytest.raises(ValueError, match=err_msg3):
PeriodIndex(ordinal=[per.ordinal], year=[per.year], freq=per.freq)

def test_construction_base_constructor(self):
# GH 13664
arr = [Period("2011-01", freq="M"), NaT, Period("2011-03", freq="M")]
Expand Down

0 comments on commit e89d18c

Please sign in to comment.