|
| 1 | +import os |
| 2 | + |
1 | 3 | import numpy as np
|
2 | 4 | import pytest
|
3 | 5 |
|
@@ -522,3 +524,49 @@ def test_loc_with_mi_indexer():
|
522 | 524 | columns=["author", "price"],
|
523 | 525 | )
|
524 | 526 | tm.assert_frame_equal(result, expected)
|
| 527 | + |
| 528 | + |
| 529 | +def test_getitem_str_slice(): |
| 530 | + # GH#15928 |
| 531 | + path = os.path.join( |
| 532 | + pd.__path__[0], "tests", "reshape", "merge", "data", "quotes2.csv" |
| 533 | + ) |
| 534 | + df = pd.read_csv(path, parse_dates=["time"]) |
| 535 | + df2 = df.set_index(["ticker", "time"]).sort_index() |
| 536 | + |
| 537 | + res = df2.loc[("AAPL", slice("2016-05-25 13:30:00")), :].droplevel(0) |
| 538 | + expected = df2.loc["AAPL"].loc[slice("2016-05-25 13:30:00"), :] |
| 539 | + tm.assert_frame_equal(res, expected) |
| 540 | + |
| 541 | + |
| 542 | +def test_3levels_leading_period_index(): |
| 543 | + # GH#24091 |
| 544 | + pi = pd.PeriodIndex( |
| 545 | + ["20181101 1100", "20181101 1200", "20181102 1300", "20181102 1400"], |
| 546 | + name="datetime", |
| 547 | + freq="B", |
| 548 | + ) |
| 549 | + lev2 = ["A", "A", "Z", "W"] |
| 550 | + lev3 = ["B", "C", "Q", "F"] |
| 551 | + mi = pd.MultiIndex.from_arrays([pi, lev2, lev3]) |
| 552 | + |
| 553 | + ser = pd.Series(range(4), index=mi, dtype=np.float64) |
| 554 | + result = ser.loc[(pi[0], "A", "B")] |
| 555 | + assert result == 0.0 |
| 556 | + |
| 557 | + |
| 558 | +class TestKeyErrorsWithMultiIndex: |
| 559 | + def test_missing_keys_raises_keyerror(self): |
| 560 | + # GH#27420 KeyError, not TypeError |
| 561 | + df = pd.DataFrame(np.arange(12).reshape(4, 3), columns=["A", "B", "C"]) |
| 562 | + df2 = df.set_index(["A", "B"]) |
| 563 | + |
| 564 | + with pytest.raises(KeyError, match="1"): |
| 565 | + df2.loc[(1, 6)] |
| 566 | + |
| 567 | + def test_missing_key_raises_keyerror2(self): |
| 568 | + # GH#21168 KeyError, not "IndexingError: Too many indexers" |
| 569 | + ser = pd.Series(-1, index=pd.MultiIndex.from_product([[0, 1]] * 2)) |
| 570 | + |
| 571 | + with pytest.raises(KeyError, match=r"\(0, 3\)"): |
| 572 | + ser.loc[0, 3] |
0 commit comments