0

Following up on this answer How to keep only a certain set of rows by index in a pandas DataFrame I need to extend it a bit:

E. g. I only want to keep rows where it's index follows a rule. In my case '01' through '99'. do I have to write a series from 01 to 99 to filter the rows? Or would be some kind of regex OK? gooddf.loc['[0-9]']

Fred
  • 417
  • 5
  • 16

1 Answers1

1

In this case, making sure that you specify the start with "^" and end of the match with "$" will be appropriate.

import pandas as pd

gooddf = pd.DataFrame({"K":[2,3,4,6,2]}, index=["01", "101", "98", "201", "032"])

match_in = gooddf.index.str.match("^[0-9]{1,2}$")
gooddf[match_in]
Lunalo John
  • 325
  • 3
  • 10