Skip to content

Commit 3946133

Browse files
jbrockmendelpull[bot]
authored andcommitted
BUG: PeriodIndex.__new__ with keyword mismatch (#55961)
* BUG: PeriodIndex.__new__ with keyword mismatch * GH refs
1 parent a601827 commit 3946133

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

doc/source/whatsnew/v2.2.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -420,6 +420,7 @@ I/O
420420

421421
Period
422422
^^^^^^
423+
- Bug in :class:`PeriodIndex` construction when more than one of ``data``, ``ordinal`` and ``**fields`` are passed failing to raise ``ValueError`` (:issue:`55961`)
423424
- Bug in :class:`Period` addition silently wrapping around instead of raising ``OverflowError`` (:issue:`55503`)
424425
- Bug in casting from :class:`PeriodDtype` with ``astype`` to ``datetime64`` or :class:`DatetimeTZDtype` with non-nanosecond unit incorrectly returning with nanosecond unit (:issue:`55958`)
425426
-

pandas/core/indexes/period.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,11 @@ def __new__(
249249

250250
dtype = PeriodDtype(freq)
251251
data = PeriodArray(data, dtype=dtype)
252+
elif fields:
253+
if data is not None:
254+
raise ValueError("Cannot pass both data and fields")
255+
raise ValueError("Cannot pass both ordinal and fields")
256+
252257
else:
253258
freq = validate_dtype_freq(dtype, freq)
254259

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

263268
if data is None and ordinal is not None:
264-
# we strangely ignore `ordinal` if data is passed.
265269
ordinal = np.asarray(ordinal, dtype=np.int64)
266270
dtype = PeriodDtype(freq)
267271
data = PeriodArray(ordinal, dtype=dtype)
272+
elif data is not None and ordinal is not None:
273+
raise ValueError("Cannot pass both data and ordinal")
268274
else:
269275
# don't pass copy here, since we copy later.
270276
data = period_array(data=data, freq=freq)

pandas/tests/indexes/period/test_constructors.py

+16
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,22 @@
2020

2121

2222
class TestPeriodIndex:
23+
def test_keyword_mismatch(self):
24+
# GH#55961 we should get exactly one of data/ordinals/**fields
25+
per = Period("2016-01-01", "D")
26+
27+
err_msg1 = "Cannot pass both data and ordinal"
28+
with pytest.raises(ValueError, match=err_msg1):
29+
PeriodIndex(data=[per], ordinal=[per.ordinal], freq=per.freq)
30+
31+
err_msg2 = "Cannot pass both data and fields"
32+
with pytest.raises(ValueError, match=err_msg2):
33+
PeriodIndex(data=[per], year=[per.year], freq=per.freq)
34+
35+
err_msg3 = "Cannot pass both ordinal and fields"
36+
with pytest.raises(ValueError, match=err_msg3):
37+
PeriodIndex(ordinal=[per.ordinal], year=[per.year], freq=per.freq)
38+
2339
def test_construction_base_constructor(self):
2440
# GH 13664
2541
arr = [Period("2011-01", freq="M"), NaT, Period("2011-03", freq="M")]

0 commit comments

Comments
 (0)