test_inference.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. from datetime import (
  2. datetime,
  3. timedelta,
  4. )
  5. import numpy as np
  6. import pytest
  7. from pandas._libs.tslibs.ccalendar import (
  8. DAYS,
  9. MONTHS,
  10. )
  11. from pandas._libs.tslibs.offsets import _get_offset
  12. from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG
  13. from pandas.compat import is_platform_windows
  14. from pandas import (
  15. DatetimeIndex,
  16. Index,
  17. Series,
  18. Timestamp,
  19. date_range,
  20. period_range,
  21. )
  22. import pandas._testing as tm
  23. from pandas.core.arrays import (
  24. DatetimeArray,
  25. TimedeltaArray,
  26. )
  27. from pandas.core.tools.datetimes import to_datetime
  28. from pandas.tseries import (
  29. frequencies,
  30. offsets,
  31. )
  32. @pytest.fixture(
  33. params=[
  34. (timedelta(1), "D"),
  35. (timedelta(hours=1), "H"),
  36. (timedelta(minutes=1), "T"),
  37. (timedelta(seconds=1), "S"),
  38. (np.timedelta64(1, "ns"), "N"),
  39. (timedelta(microseconds=1), "U"),
  40. (timedelta(microseconds=1000), "L"),
  41. ]
  42. )
  43. def base_delta_code_pair(request):
  44. return request.param
  45. freqs = (
  46. [f"Q-{month}" for month in MONTHS]
  47. + [f"{annual}-{month}" for annual in ["A", "BA"] for month in MONTHS]
  48. + ["M", "BM", "BMS"]
  49. + [f"WOM-{count}{day}" for count in range(1, 5) for day in DAYS]
  50. + [f"W-{day}" for day in DAYS]
  51. )
  52. @pytest.mark.parametrize("freq", freqs)
  53. @pytest.mark.parametrize("periods", [5, 7])
  54. def test_infer_freq_range(periods, freq):
  55. freq = freq.upper()
  56. gen = date_range("1/1/2000", periods=periods, freq=freq)
  57. index = DatetimeIndex(gen.values)
  58. if not freq.startswith("Q-"):
  59. assert frequencies.infer_freq(index) == gen.freqstr
  60. else:
  61. inf_freq = frequencies.infer_freq(index)
  62. is_dec_range = inf_freq == "Q-DEC" and gen.freqstr in (
  63. "Q",
  64. "Q-DEC",
  65. "Q-SEP",
  66. "Q-JUN",
  67. "Q-MAR",
  68. )
  69. is_nov_range = inf_freq == "Q-NOV" and gen.freqstr in (
  70. "Q-NOV",
  71. "Q-AUG",
  72. "Q-MAY",
  73. "Q-FEB",
  74. )
  75. is_oct_range = inf_freq == "Q-OCT" and gen.freqstr in (
  76. "Q-OCT",
  77. "Q-JUL",
  78. "Q-APR",
  79. "Q-JAN",
  80. )
  81. assert is_dec_range or is_nov_range or is_oct_range
  82. def test_raise_if_period_index():
  83. index = period_range(start="1/1/1990", periods=20, freq="M")
  84. msg = "Check the `freq` attribute instead of using infer_freq"
  85. with pytest.raises(TypeError, match=msg):
  86. frequencies.infer_freq(index)
  87. def test_raise_if_too_few():
  88. index = DatetimeIndex(["12/31/1998", "1/3/1999"])
  89. msg = "Need at least 3 dates to infer frequency"
  90. with pytest.raises(ValueError, match=msg):
  91. frequencies.infer_freq(index)
  92. def test_business_daily():
  93. index = DatetimeIndex(["01/01/1999", "1/4/1999", "1/5/1999"])
  94. assert frequencies.infer_freq(index) == "B"
  95. def test_business_daily_look_alike():
  96. # see gh-16624
  97. #
  98. # Do not infer "B when "weekend" (2-day gap) in wrong place.
  99. index = DatetimeIndex(["12/31/1998", "1/3/1999", "1/4/1999"])
  100. assert frequencies.infer_freq(index) is None
  101. def test_day_corner():
  102. index = DatetimeIndex(["1/1/2000", "1/2/2000", "1/3/2000"])
  103. assert frequencies.infer_freq(index) == "D"
  104. def test_non_datetime_index():
  105. dates = to_datetime(["1/1/2000", "1/2/2000", "1/3/2000"])
  106. assert frequencies.infer_freq(dates) == "D"
  107. def test_fifth_week_of_month_infer():
  108. # see gh-9425
  109. #
  110. # Only attempt to infer up to WOM-4.
  111. index = DatetimeIndex(["2014-03-31", "2014-06-30", "2015-03-30"])
  112. assert frequencies.infer_freq(index) is None
  113. def test_week_of_month_fake():
  114. # All of these dates are on same day
  115. # of week and are 4 or 5 weeks apart.
  116. index = DatetimeIndex(["2013-08-27", "2013-10-01", "2013-10-29", "2013-11-26"])
  117. assert frequencies.infer_freq(index) != "WOM-4TUE"
  118. def test_fifth_week_of_month():
  119. # see gh-9425
  120. #
  121. # Only supports freq up to WOM-4.
  122. msg = (
  123. "Of the four parameters: start, end, periods, "
  124. "and freq, exactly three must be specified"
  125. )
  126. with pytest.raises(ValueError, match=msg):
  127. date_range("2014-01-01", freq="WOM-5MON")
  128. def test_monthly_ambiguous():
  129. rng = DatetimeIndex(["1/31/2000", "2/29/2000", "3/31/2000"])
  130. assert rng.inferred_freq == "M"
  131. def test_annual_ambiguous():
  132. rng = DatetimeIndex(["1/31/2000", "1/31/2001", "1/31/2002"])
  133. assert rng.inferred_freq == "A-JAN"
  134. @pytest.mark.parametrize("count", range(1, 5))
  135. def test_infer_freq_delta(base_delta_code_pair, count):
  136. b = Timestamp(datetime.now())
  137. base_delta, code = base_delta_code_pair
  138. inc = base_delta * count
  139. index = DatetimeIndex([b + inc * j for j in range(3)])
  140. exp_freq = f"{count:d}{code}" if count > 1 else code
  141. assert frequencies.infer_freq(index) == exp_freq
  142. @pytest.mark.parametrize(
  143. "constructor",
  144. [
  145. lambda now, delta: DatetimeIndex(
  146. [now + delta * 7] + [now + delta * j for j in range(3)]
  147. ),
  148. lambda now, delta: DatetimeIndex(
  149. [now + delta * j for j in range(3)] + [now + delta * 7]
  150. ),
  151. ],
  152. )
  153. def test_infer_freq_custom(base_delta_code_pair, constructor):
  154. b = Timestamp(datetime.now())
  155. base_delta, _ = base_delta_code_pair
  156. index = constructor(b, base_delta)
  157. assert frequencies.infer_freq(index) is None
  158. @pytest.mark.parametrize(
  159. "freq,expected", [("Q", "Q-DEC"), ("Q-NOV", "Q-NOV"), ("Q-OCT", "Q-OCT")]
  160. )
  161. def test_infer_freq_index(freq, expected):
  162. rng = period_range("1959Q2", "2009Q3", freq=freq)
  163. rng = Index(rng.to_timestamp("D", how="e").astype(object))
  164. assert rng.inferred_freq == expected
  165. @pytest.mark.parametrize(
  166. "expected,dates",
  167. list(
  168. {
  169. "AS-JAN": ["2009-01-01", "2010-01-01", "2011-01-01", "2012-01-01"],
  170. "Q-OCT": ["2009-01-31", "2009-04-30", "2009-07-31", "2009-10-31"],
  171. "M": ["2010-11-30", "2010-12-31", "2011-01-31", "2011-02-28"],
  172. "W-SAT": ["2010-12-25", "2011-01-01", "2011-01-08", "2011-01-15"],
  173. "D": ["2011-01-01", "2011-01-02", "2011-01-03", "2011-01-04"],
  174. "H": [
  175. "2011-12-31 22:00",
  176. "2011-12-31 23:00",
  177. "2012-01-01 00:00",
  178. "2012-01-01 01:00",
  179. ],
  180. }.items()
  181. ),
  182. )
  183. def test_infer_freq_tz(tz_naive_fixture, expected, dates):
  184. # see gh-7310
  185. tz = tz_naive_fixture
  186. idx = DatetimeIndex(dates, tz=tz)
  187. assert idx.inferred_freq == expected
  188. @pytest.mark.parametrize(
  189. "date_pair",
  190. [
  191. ["2013-11-02", "2013-11-5"], # Fall DST
  192. ["2014-03-08", "2014-03-11"], # Spring DST
  193. ["2014-01-01", "2014-01-03"], # Regular Time
  194. ],
  195. )
  196. @pytest.mark.parametrize(
  197. "freq", ["H", "3H", "10T", "3601S", "3600001L", "3600000001U", "3600000000001N"]
  198. )
  199. def test_infer_freq_tz_transition(tz_naive_fixture, date_pair, freq):
  200. # see gh-8772
  201. tz = tz_naive_fixture
  202. idx = date_range(date_pair[0], date_pair[1], freq=freq, tz=tz)
  203. assert idx.inferred_freq == freq
  204. def test_infer_freq_tz_transition_custom():
  205. index = date_range("2013-11-03", periods=5, freq="3H").tz_localize(
  206. "America/Chicago"
  207. )
  208. assert index.inferred_freq is None
  209. @pytest.mark.parametrize(
  210. "data,expected",
  211. [
  212. # Hourly freq in a day must result in "H"
  213. (
  214. [
  215. "2014-07-01 09:00",
  216. "2014-07-01 10:00",
  217. "2014-07-01 11:00",
  218. "2014-07-01 12:00",
  219. "2014-07-01 13:00",
  220. "2014-07-01 14:00",
  221. ],
  222. "H",
  223. ),
  224. (
  225. [
  226. "2014-07-01 09:00",
  227. "2014-07-01 10:00",
  228. "2014-07-01 11:00",
  229. "2014-07-01 12:00",
  230. "2014-07-01 13:00",
  231. "2014-07-01 14:00",
  232. "2014-07-01 15:00",
  233. "2014-07-01 16:00",
  234. "2014-07-02 09:00",
  235. "2014-07-02 10:00",
  236. "2014-07-02 11:00",
  237. ],
  238. "BH",
  239. ),
  240. (
  241. [
  242. "2014-07-04 09:00",
  243. "2014-07-04 10:00",
  244. "2014-07-04 11:00",
  245. "2014-07-04 12:00",
  246. "2014-07-04 13:00",
  247. "2014-07-04 14:00",
  248. "2014-07-04 15:00",
  249. "2014-07-04 16:00",
  250. "2014-07-07 09:00",
  251. "2014-07-07 10:00",
  252. "2014-07-07 11:00",
  253. ],
  254. "BH",
  255. ),
  256. (
  257. [
  258. "2014-07-04 09:00",
  259. "2014-07-04 10:00",
  260. "2014-07-04 11:00",
  261. "2014-07-04 12:00",
  262. "2014-07-04 13:00",
  263. "2014-07-04 14:00",
  264. "2014-07-04 15:00",
  265. "2014-07-04 16:00",
  266. "2014-07-07 09:00",
  267. "2014-07-07 10:00",
  268. "2014-07-07 11:00",
  269. "2014-07-07 12:00",
  270. "2014-07-07 13:00",
  271. "2014-07-07 14:00",
  272. "2014-07-07 15:00",
  273. "2014-07-07 16:00",
  274. "2014-07-08 09:00",
  275. "2014-07-08 10:00",
  276. "2014-07-08 11:00",
  277. "2014-07-08 12:00",
  278. "2014-07-08 13:00",
  279. "2014-07-08 14:00",
  280. "2014-07-08 15:00",
  281. "2014-07-08 16:00",
  282. ],
  283. "BH",
  284. ),
  285. ],
  286. )
  287. def test_infer_freq_business_hour(data, expected):
  288. # see gh-7905
  289. idx = DatetimeIndex(data)
  290. assert idx.inferred_freq == expected
  291. def test_not_monotonic():
  292. rng = DatetimeIndex(["1/31/2000", "1/31/2001", "1/31/2002"])
  293. rng = rng[::-1]
  294. assert rng.inferred_freq == "-1A-JAN"
  295. def test_non_datetime_index2():
  296. rng = DatetimeIndex(["1/31/2000", "1/31/2001", "1/31/2002"])
  297. vals = rng.to_pydatetime()
  298. result = frequencies.infer_freq(vals)
  299. assert result == rng.inferred_freq
  300. @pytest.mark.parametrize(
  301. "idx",
  302. [
  303. tm.makeIntIndex(10),
  304. tm.makeFloatIndex(10),
  305. tm.makePeriodIndex(10),
  306. tm.makeRangeIndex(10),
  307. ],
  308. )
  309. def test_invalid_index_types(idx):
  310. # see gh-48439
  311. msg = "|".join(
  312. [
  313. "cannot infer freq from a non-convertible",
  314. "Check the `freq` attribute instead of using infer_freq",
  315. ]
  316. )
  317. with pytest.raises(TypeError, match=msg):
  318. frequencies.infer_freq(idx)
  319. @pytest.mark.skipif(is_platform_windows(), reason="see gh-10822: Windows issue")
  320. def test_invalid_index_types_unicode():
  321. # see gh-10822
  322. #
  323. # Odd error message on conversions to datetime for unicode.
  324. msg = "Unknown datetime string format"
  325. with pytest.raises(ValueError, match=msg):
  326. frequencies.infer_freq(tm.makeStringIndex(10))
  327. def test_string_datetime_like_compat():
  328. # see gh-6463
  329. data = ["2004-01", "2004-02", "2004-03", "2004-04"]
  330. expected = frequencies.infer_freq(data)
  331. result = frequencies.infer_freq(Index(data))
  332. assert result == expected
  333. def test_series():
  334. # see gh-6407
  335. s = Series(date_range("20130101", "20130110"))
  336. inferred = frequencies.infer_freq(s)
  337. assert inferred == "D"
  338. @pytest.mark.parametrize("end", [10, 10.0])
  339. def test_series_invalid_type(end):
  340. # see gh-6407
  341. msg = "cannot infer freq from a non-convertible dtype on a Series"
  342. s = Series(np.arange(end))
  343. with pytest.raises(TypeError, match=msg):
  344. frequencies.infer_freq(s)
  345. def test_series_inconvertible_string():
  346. # see gh-6407
  347. msg = "Unknown datetime string format"
  348. with pytest.raises(ValueError, match=msg):
  349. frequencies.infer_freq(Series(["foo", "bar"]))
  350. @pytest.mark.parametrize("freq", [None, "L"])
  351. def test_series_period_index(freq):
  352. # see gh-6407
  353. #
  354. # Cannot infer on PeriodIndex
  355. msg = "cannot infer freq from a non-convertible dtype on a Series"
  356. s = Series(period_range("2013", periods=10, freq=freq))
  357. with pytest.raises(TypeError, match=msg):
  358. frequencies.infer_freq(s)
  359. @pytest.mark.parametrize("freq", ["M", "L", "S"])
  360. def test_series_datetime_index(freq):
  361. s = Series(date_range("20130101", periods=10, freq=freq))
  362. inferred = frequencies.infer_freq(s)
  363. assert inferred == freq
  364. @pytest.mark.parametrize(
  365. "offset_func",
  366. [
  367. _get_offset,
  368. lambda freq: date_range("2011-01-01", periods=5, freq=freq),
  369. ],
  370. )
  371. @pytest.mark.parametrize(
  372. "freq",
  373. [
  374. "WEEKDAY",
  375. "EOM",
  376. "W@MON",
  377. "W@TUE",
  378. "W@WED",
  379. "W@THU",
  380. "W@FRI",
  381. "W@SAT",
  382. "W@SUN",
  383. "Q@JAN",
  384. "Q@FEB",
  385. "Q@MAR",
  386. "A@JAN",
  387. "A@FEB",
  388. "A@MAR",
  389. "A@APR",
  390. "A@MAY",
  391. "A@JUN",
  392. "A@JUL",
  393. "A@AUG",
  394. "A@SEP",
  395. "A@OCT",
  396. "A@NOV",
  397. "A@DEC",
  398. "Y@JAN",
  399. "WOM@1MON",
  400. "WOM@2MON",
  401. "WOM@3MON",
  402. "WOM@4MON",
  403. "WOM@1TUE",
  404. "WOM@2TUE",
  405. "WOM@3TUE",
  406. "WOM@4TUE",
  407. "WOM@1WED",
  408. "WOM@2WED",
  409. "WOM@3WED",
  410. "WOM@4WED",
  411. "WOM@1THU",
  412. "WOM@2THU",
  413. "WOM@3THU",
  414. "WOM@4THU",
  415. "WOM@1FRI",
  416. "WOM@2FRI",
  417. "WOM@3FRI",
  418. "WOM@4FRI",
  419. ],
  420. )
  421. def test_legacy_offset_warnings(offset_func, freq):
  422. with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG):
  423. offset_func(freq)
  424. def test_ms_vs_capital_ms():
  425. left = _get_offset("ms")
  426. right = _get_offset("MS")
  427. assert left == offsets.Milli()
  428. assert right == offsets.MonthBegin()
  429. def test_infer_freq_non_nano():
  430. arr = np.arange(10).astype(np.int64).view("M8[s]")
  431. dta = DatetimeArray._simple_new(arr, dtype=arr.dtype)
  432. res = frequencies.infer_freq(dta)
  433. assert res == "S"
  434. arr2 = arr.view("m8[ms]")
  435. tda = TimedeltaArray._simple_new(arr2, dtype=arr2.dtype)
  436. res2 = frequencies.infer_freq(tda)
  437. assert res2 == "L"
  438. def test_infer_freq_non_nano_tzaware(tz_aware_fixture):
  439. tz = tz_aware_fixture
  440. dti = date_range("2016-01-01", periods=365, freq="B", tz=tz)
  441. dta = dti._data.as_unit("s")
  442. res = frequencies.infer_freq(dta)
  443. assert res == "B"