Skip to content

ENH: column label filtering via regexes to work for numeric names #10384

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

Closed
wants to merge 18 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
3 changes: 2 additions & 1 deletion doc/source/whatsnew/v0.17.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ New features

Other enhancements
^^^^^^^^^^^^^^^^^^

- ``regex`` argument to ``DataFrame.filter`` now handles numeric column names instead of raising ``ValueError`` (:issue:`10384`).

.. _whatsnew_0170.api:

Backwards incompatible API changes
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1928,7 +1928,7 @@ def filter(self, items=None, like=None, regex=None, axis=None):
return self.select(matchf, axis=axis_name)
elif regex:
matcher = re.compile(regex)
return self.select(lambda x: matcher.search(x) is not None,
return self.select(lambda x: matcher.search(str(x)) is not None,
axis=axis_name)
else:
raise TypeError('Must pass either `items`, `like`, or `regex`')
Expand Down
13 changes: 12 additions & 1 deletion pandas/tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -10741,7 +10741,7 @@ def test_filter(self):
idx = self.frame.index[0:4]
filtered = self.frame.filter(idx, axis='index')
expected = self.frame.reindex(index=idx)
assert_frame_equal(filtered,expected)
assert_frame_equal(filtered, expected)

# like
fcopy = self.frame.copy()
Expand All @@ -10755,6 +10755,17 @@ def test_filter(self):
df = DataFrame(0., index=[0, 1, 2], columns=[0, 1, '_A', '_B'])
filtered = df.filter(like='_')
self.assertEqual(len(filtered.columns), 2)

# regex with ints in column names
# from PR #10384
df = DataFrame(0., index=[0, 1, 2], columns=['A1', 1, 'B', 2, 'C'])
expected = DataFrame(0., index=[0, 1, 2], columns=[1, 2])
filtered = df.filter(regex='^[0-9]+$')
self.assert_frame_equal(filtered, expected)

expected = DataFrame(0., index=[0, 1, 2], columns=[0, 1, '0', '1'])
filtered = expected.filter(regex='^[0-9]+$') # shouldn't remove anything
self.assert_frame_equal(filtered, expected)

# pass in None
with assertRaisesRegexp(TypeError, 'Must pass'):
Expand Down