Che Liang
Che Liang

Reputation: 13

Matching list of strings in my variables to my pandas table

So i have these list of variables in my table['title']

    title
0   Intern, Ops System
1   Regional Business Analyst, Fleet
2   Analyst, Performance Monitoring & Planning (PMP)
3   Designer (Contract)
4   Fashion Category Intern
5   Expert Recruiter (Contract)
6   Category Executive - Groceries
7   Guided Sales - Various Categories (Contract)
8   Category Executive - Muslimahwear (Contract)
9   Category Executive - Mother & Baby (Contract)

In my program, I'm trying to give the users a dropdown list of options which has the titles. So users are able to choose title(s) which would create a new table showcasing what they have chosen. Below is my code:

values = ["Intern, Ops System","Analyst, Performance Monitoring & Planning (PMP)","Fashion Category Intern","Guided Sales - Various Categories (Contract)"]

variables = "|".join(values)

filtered_table = table[table['title'].str.contains(variables, regex = True)]

I tried using this method to get my solution but somehow it only manages to show titles that does not have parenthesis in it's name

    title   
0   Intern, Ops System  
4   Fashion Category Intern

Is there any way where I could get it all to show up in my filtered_table?

Upvotes: 1

Views: 33

Answers (1)

jezrael
jezrael

Reputation: 863256

Because () are special regex characters add re.escape in generator comprehension for escape all special regex values:

import re
variables = "|".join(re.escape(x) for x in values)

filtered_table = table[table['title'].str.contains(variables, regex = True)]
print (filtered_table)
                                              title
0                                Intern, Ops System
2  Analyst, Performance Monitoring & Planning (PMP)
4                           Fashion Category Intern
7      Guided Sales - Various Categories (Contract)

Upvotes: 1

Related Questions