How can a Pandas DataFrame be filtered using patterns?

Viewed 43

Is there a way to filter Pandas DataFrame rows using wildcard patterns?

Example initial state of the data.

df = pd.DataFrame([
    ['noun','nominative','singular','m','',''],
    ['noun','nominative','singular','f','',''],
    ['noun','nominative','singular','n','',''],
    ['noun','accusative','singular','n','',''],
    ['noun','accusative','singular','n','',''],
    ['noun','accusative','singular','n','',''],
    ['verb','','singular','','present','1per'],
    ['verb','','singular','','present','2per'],
    ['verb','','singular','','present','3per'],
    ['verb','','plural','','present','1per'],
    ['verb','','plural','','present','2per'],
    ['verb','','plural','','present','3per'],
],columns=['pos', 'case', 'number', 'gender', 'tense', 'person'])
mask = pd.Series(['noun','nominative','singular','*','',''])

Objective end state of data:

['noun','nominative','singular','m','',''],
['noun','nominative','singular','f','',''],
['noun','nominative','singular','n','',''],
1 Answers

You can just leave out the wildcard column when you do the comparison:

pattern = ['noun', 'nominative', 'singular', '', '']
cols_to_match = ['pos', 'case', 'number', 'tense', 'person']

mask = (df[cols_to_match] == pattern).all(axis=1)
df_filtered = df[mask]
Related