Skip to content

Commit 562db37

Browse files
phoflmeeseeksmachine
authored andcommitted
Backport PR pandas-dev#54982: REG: filter not respecting the order of labels
1 parent e0534b3 commit 562db37

File tree

3 files changed

+20
-3
lines changed

3 files changed

+20
-3
lines changed

doc/source/whatsnew/v2.1.1.rst

+1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ Fixed regressions
1818
- Fixed regression in :func:`read_csv` when ``delim_whitespace`` is True (:issue:`54918`, :issue:`54931`)
1919
- Fixed regression in :meth:`.GroupBy.get_group` raising for ``axis=1`` (:issue:`54858`)
2020
- Fixed regression in :meth:`DataFrame.__setitem__` raising ``AssertionError`` when setting a :class:`Series` with a partial :class:`MultiIndex` (:issue:`54875`)
21+
- Fixed regression in :meth:`DataFrame.filter` not respecting the order of elements for ``filter`` (:issue:`54980`)
2122
- Fixed regression in :meth:`DataFrame.to_sql` not roundtripping datetime columns correctly for sqlite (:issue:`54877`)
2223
- Fixed regression in :meth:`MultiIndex.append` raising when appending overlapping :class:`IntervalIndex` levels (:issue:`54934`)
2324
- Fixed regression in :meth:`Series.drop_duplicates` for PyArrow strings (:issue:`54904`)

pandas/core/generic.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -5701,10 +5701,12 @@ def filter(
57015701

57025702
if items is not None:
57035703
name = self._get_axis_name(axis)
5704+
items = Index(items).intersection(labels)
5705+
if len(items) == 0:
5706+
# Keep the dtype of labels when we are empty
5707+
items = items.astype(labels.dtype)
57045708
# error: Keywords must be strings
5705-
return self.reindex( # type: ignore[misc]
5706-
**{name: labels.intersection(items)}
5707-
)
5709+
return self.reindex(**{name: items}) # type: ignore[misc]
57085710
elif like:
57095711

57105712
def f(x) -> bool_t:

pandas/tests/frame/methods/test_filter.py

+14
Original file line numberDiff line numberDiff line change
@@ -137,3 +137,17 @@ def test_filter_regex_non_string(self):
137137
result = df.filter(regex="STRING")
138138
expected = df[["STRING"]]
139139
tm.assert_frame_equal(result, expected)
140+
141+
def test_filter_keep_order(self):
142+
# GH#54980
143+
df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
144+
result = df.filter(items=["B", "A"])
145+
expected = df[["B", "A"]]
146+
tm.assert_frame_equal(result, expected)
147+
148+
def test_filter_different_dtype(self):
149+
# GH#54980
150+
df = DataFrame({1: [1, 2, 3], 2: [4, 5, 6]})
151+
result = df.filter(items=["B", "A"])
152+
expected = df[[]]
153+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)