|
3 | 3 | import pytest
|
4 | 4 |
|
5 | 5 | import numpy as np
|
| 6 | +from numpy import testing as ntm |
6 | 7 | import pandas as pd
|
7 | 8 | from pandas.util import testing as tm
|
8 | 9 | from pandas.compat import lrange
|
9 |
| -from pandas._libs import tslib |
| 10 | +from pandas._libs import tslib, tslibs |
10 | 11 | from pandas import (PeriodIndex, Series, DatetimeIndex,
|
11 | 12 | period_range, Period)
|
12 | 13 |
|
@@ -340,3 +341,34 @@ def test_truncate(self):
|
340 | 341 | pd.Period('2017-09-02')
|
341 | 342 | ])
|
342 | 343 | tm.assert_series_equal(result2, pd.Series([1, 2], index=expected_idx2))
|
| 344 | + |
| 345 | + def test_get_loc(self): |
| 346 | + # GH 17717 |
| 347 | + p1 = pd.Period('2017-09-02') |
| 348 | + p2 = pd.Period('2017-09-03') |
| 349 | + |
| 350 | + idx1 = pd.PeriodIndex([p1, p1, p2]) |
| 351 | + expected_idx1_p1 = slice(0, 2) |
| 352 | + expected_idx1_p2 = 2 |
| 353 | + |
| 354 | + assert idx1.get_loc(p1) == expected_idx1_p1 |
| 355 | + assert idx1.get_loc(str(p1)) == expected_idx1_p1 |
| 356 | + assert idx1.get_loc(p1.ordinal) == expected_idx1_p1 |
| 357 | + assert idx1.get_loc(p2) == expected_idx1_p2 |
| 358 | + assert idx1.get_loc(str(p2)) == expected_idx1_p2 |
| 359 | + assert idx1.get_loc(p2.ordinal) == expected_idx1_p2 |
| 360 | + |
| 361 | + pytest.raises(tslibs.parsing.DateParseError, idx1.get_loc, 'foo') |
| 362 | + pytest.raises(KeyError, idx1.get_loc, 1.1) |
| 363 | + pytest.raises(TypeError, idx1.get_loc, idx1) |
| 364 | + |
| 365 | + idx2 = pd.PeriodIndex([p2, p1, p2]) |
| 366 | + expected_idx2_p1 = 1 |
| 367 | + expected_idx2_p2 = np.array([True, False, True]) |
| 368 | + |
| 369 | + assert idx2.get_loc(p1) == expected_idx2_p1 |
| 370 | + assert idx2.get_loc(str(p1)) == expected_idx2_p1 |
| 371 | + assert idx2.get_loc(p1.ordinal) == expected_idx2_p1 |
| 372 | + ntm.assert_array_equal(idx2.get_loc(p2), expected_idx2_p2) |
| 373 | + ntm.assert_array_equal(idx2.get_loc(str(p2)), expected_idx2_p2) |
| 374 | + ntm.assert_array_equal(idx2.get_loc(p2.ordinal), expected_idx2_p2) |
0 commit comments