Skip to content

DataFrame.truncate drops MultiIndex names #34589

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Jun 20, 2020
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -911,6 +911,7 @@ MultiIndex
df.loc[(['b', 'a'], [2, 1]), :]

- Bug in :meth:`MultiIndex.intersection` was not guaranteed to preserve order when ``sort=False``. (:issue:`31325`)
- Bug in :meth:`DataFrame.truncate` was dropping :class:`MultiIndex` names. (:issue:`34564`)

.. ipython:: python

Expand Down
7 changes: 6 additions & 1 deletion pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -3195,7 +3195,12 @@ def truncate(self, before=None, after=None):
new_codes = [level_codes[left:right] for level_codes in self.codes]
new_codes[0] = new_codes[0] - i

return MultiIndex(levels=new_levels, codes=new_codes, verify_integrity=False)
return MultiIndex(
levels=new_levels,
codes=new_codes,
names=self._names,
verify_integrity=False,
)

def equals(self, other) -> bool:
"""
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/frame/methods/test_truncate.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,15 @@ def test_truncate_decreasing_index(self, before, after, indices, klass):
result = values.truncate(before=before, after=after)
expected = values.loc[indices]
tm.assert_frame_equal(result, expected)

def test_truncate_multiindex(self):
mi = pd.MultiIndex.from_product([[1, 2, 3, 4], ["A", "B"]], names=["L1", "L2"])
s1 = pd.DataFrame(range(mi.shape[0]), index=mi, columns=["col"])
result = s1.truncate(before=2, after=3)

df = pd.DataFrame.from_dict(
{"L1": [2, 2, 3, 3], "L2": ["A", "B", "A", "B"], "col": [2, 3, 4, 5]}
)
expected = df.set_index(["L1", "L2"])

tm.assert_frame_equal(result, expected)
8 changes: 7 additions & 1 deletion pandas/tests/indexes/multi/test_analytics.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,26 +31,32 @@ def test_groupby(idx):


def test_truncate():
# GH 34564 for MultiIndex level names check
major_axis = Index(list(range(4)))
minor_axis = Index(list(range(2)))

major_codes = np.array([0, 0, 1, 2, 3, 3])
minor_codes = np.array([0, 1, 0, 1, 0, 1])

index = MultiIndex(
levels=[major_axis, minor_axis], codes=[major_codes, minor_codes]
levels=[major_axis, minor_axis],
codes=[major_codes, minor_codes],
names=["L1", "L2"],
)

result = index.truncate(before=1)
assert "foo" not in result.levels[0]
assert 1 in result.levels[0]
assert index.names == result.names

result = index.truncate(after=1)
assert 2 not in result.levels[0]
assert 1 in result.levels[0]
assert index.names == result.names

result = index.truncate(before=1, after=2)
assert len(result.levels[0]) == 2
assert index.names == result.names

msg = "after < before"
with pytest.raises(ValueError, match=msg):
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/indexing/multiindex/test_slice.py
Original file line number Diff line number Diff line change
Expand Up @@ -744,3 +744,11 @@ def test_non_reducing_slice_on_multiindex(self):
result = df.loc[tslice_]
expected = pd.DataFrame({("b", "d"): [4, 1]})
tm.assert_frame_equal(result, expected)

def test_truncate_multiindex_names(self):
# GH 34564

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this tests is duplicative can remove

mi = pd.MultiIndex.from_product([[1, 2, 3, 4], ["A", "B"]], names=["L1", "L2"])
s1 = pd.Series(range(mi.shape[0]), index=mi)
s2 = s1.truncate(before=2, after=3)
assert s1.index.names == s2.index.names
13 changes: 13 additions & 0 deletions pandas/tests/series/methods/test_truncate.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,16 @@ def test_truncate_periodindex(self):

expected_idx2 = pd.PeriodIndex([pd.Period("2017-09-02")])
tm.assert_series_equal(result2, pd.Series([2], index=expected_idx2))

def test_truncate_multiindex(self):
mi = pd.MultiIndex.from_product([[1, 2, 3, 4], ["A", "B"]], names=["L1", "L2"])
s1 = pd.Series(range(mi.shape[0]), index=mi, name="col")
result = s1.truncate(before=2, after=3)

df = pd.DataFrame.from_dict(
{"L1": [2, 2, 3, 3], "L2": ["A", "B", "A", "B"], "col": [2, 3, 4, 5]}
)
df.set_index(["L1", "L2"], inplace=True)
expected = df.col

tm.assert_series_equal(result, expected)