Skip to content
Advertisement

Python Regex DataFrame match

I have a DataFrame and I would like to perform a sorting if the match between my regex and the name of one of the lines of this DataFrame matches. Is there an option in the “re” library to help me? I try with this piece of code but without success Thank you in advance for your answers

regex = r"D.*cube"

for row in range(len(df)):
    for col in range(len(df.columns)):
        
        if df.iloc[row, col] == regex:
          #treatment...
          .............
    
    

Advertisement

Answer

I think you probably want

pattern = r"D.*cube"

for row in range(len(df)):
    for col in range(len(df.columns)):
        
        if re.match(pattern, df.iloc[row, col]):
          #treatment...
          .............
    
Advertisement