Skip to content

Commit da849a9

Browse files
authored
REG: filter not respecting the order of labels (#54982)
1 parent 1b3ebe4 commit da849a9

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
@@ -19,6 +19,7 @@ Fixed regressions
1919
- Fixed regression in :func:`read_csv` when ``delim_whitespace`` is True (:issue:`54918`, :issue:`54931`)
2020
- Fixed regression in :meth:`.GroupBy.get_group` raising for ``axis=1`` (:issue:`54858`)
2121
- Fixed regression in :meth:`DataFrame.__setitem__` raising ``AssertionError`` when setting a :class:`Series` with a partial :class:`MultiIndex` (:issue:`54875`)
22+
- Fixed regression in :meth:`DataFrame.filter` not respecting the order of elements for ``filter`` (:issue:`54980`)
2223
- Fixed regression in :meth:`DataFrame.to_sql` not roundtripping datetime columns correctly for sqlite (:issue:`54877`)
2324
- Fixed regression in :meth:`MultiIndex.append` raising when appending overlapping :class:`IntervalIndex` levels (:issue:`54934`)
2425
- 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
@@ -5718,10 +5718,12 @@ def filter(
57185718

57195719
if items is not None:
57205720
name = self._get_axis_name(axis)
5721+
items = Index(items).intersection(labels)
5722+
if len(items) == 0:
5723+
# Keep the dtype of labels when we are empty
5724+
items = items.astype(labels.dtype)
57215725
# error: Keywords must be strings
5722-
return self.reindex( # type: ignore[misc]
5723-
**{name: labels.intersection(items)}
5724-
)
5726+
return self.reindex(**{name: items}) # type: ignore[misc]
57255727
elif like:
57265728

57275729
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)