Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using regex with dataframes to match exact instead of just contains

My code here:

   for x in validUnitNames:
    unitDf = df.filter(regex=x)
    print(unitDf)

For the first value of x (‘BMP AHU-1’) is turning up this:

BMP AHU-1\MAT  BMP AHU-1\RAT  BMP AHU-10\MAT  BMP AHU-10\RAT  \
0        66.341175      65.131525       70.789092       68.373683   

Which works except that I only want the BMP AHU-1\ columns, not the BMP AHU-10\ columns.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How should I fix my regex statement so only include exact matches, not just contains? BMP AHU-10 comes up later in validUnitNames and will be grabbed then.

>Solution :

Make your regex ends with a backward slash:

unitDf = df.filter(regex=x + r"\\")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading