'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.

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 1:[1]

Make your regex ends with a backward slash:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Code Different