Skip to content

Commit 96b1cad

Browse files
committed
Merge pull request #5847 from jseabold/fix-5841
ENH: Improve error message for PeriodIndex to infer_freq. Closes #5841.
2 parents f7bdd34 + 32766d6 commit 96b1cad

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

pandas/tseries/frequencies.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -358,7 +358,7 @@ def get_offset(name):
358358
else:
359359
if name in _rule_aliases:
360360
name = _rule_aliases[name]
361-
361+
362362
if name not in _offset_map:
363363
try:
364364
# generate and cache offset
@@ -625,7 +625,7 @@ def _period_str_to_code(freqstr):
625625
alias = _period_alias_dict[freqstr]
626626
except KeyError:
627627
raise ValueError("Unknown freqstr: %s" % freqstr)
628-
628+
629629
return _period_code_map[alias]
630630

631631

@@ -647,6 +647,10 @@ def infer_freq(index, warn=True):
647647
from pandas.tseries.index import DatetimeIndex
648648

649649
if not isinstance(index, DatetimeIndex):
650+
from pandas.tseries.period import PeriodIndex
651+
if isinstance(index, PeriodIndex):
652+
raise ValueError("PeriodIndex given. Check the `freq` attribute "
653+
"instead of using infer_freq.")
650654
index = DatetimeIndex(index)
651655

652656
inferer = _FrequencyInferer(index, warn=warn)
@@ -850,7 +854,7 @@ def _get_wom_rule(self):
850854
weekdays = unique(self.index.weekday)
851855
if len(weekdays) > 1:
852856
return None
853-
857+
854858
week_of_months = unique((self.index.day - 1) // 7)
855859
if len(week_of_months) > 1:
856860
return None

pandas/tseries/tests/test_frequencies.py

+5
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from pandas.tseries.tools import to_datetime
1414
import pandas.tseries.frequencies as fmod
1515
import pandas.tseries.offsets as offsets
16+
from pandas.tseries.period import PeriodIndex
1617

1718
import pandas.lib as lib
1819

@@ -88,6 +89,10 @@ def test_anchored_shortcuts():
8889

8990
class TestFrequencyInference(tm.TestCase):
9091

92+
def test_raise_if_period_index(self):
93+
index = PeriodIndex(start="1/1/1990", periods=20, freq="M")
94+
self.assertRaises(ValueError, infer_freq, index)
95+
9196
def test_raise_if_too_few(self):
9297
index = _dti(['12/31/1998', '1/3/1999'])
9398
self.assertRaises(ValueError, infer_freq, index)

0 commit comments

Comments
 (0)