I am getting Attribute error in fullmatch() while extract() is working fine

Viewed 38

I am using pandas Series.str.extract(pattern) and Series.str.fullmatch(pattern) for checking if values in series are existing in pattern or not. Extract() is working fine, however fullmatch() is giving me AttributeError.

import pandas as pd

data = {'col1': ['aa', 'aabc', 'ee']}
df = pd.DataFrame(data)
print(df)

pat_data = {'name': ['aa', 'bb', 'cc']}
df_p = pd.DataFrame(pat_data)
print(df_p)

pat = "|".join(map(str,df_p['name']))
print(pat)

# This one works fine 
df['col1'].str.extract('(' + pat + ')', expand=False)

# This one gives attribute error
df['col1'].str.fullmatch('(' + pat + ')')

Output: col1 0 aa 1 aabc 2 ee name 0 aa 1 bb 2 cc aa|bb|cc

AttributeError                            Traceback (most recent call last)
<ipython-input-13-e220391b2576> in <module>()
     16 
     17 # This one gives attribute error
---> 18 df['col1'].str.fullmatch('(' + pat + ')')

AttributeError: 'StringMethods' object has no attribute 'fullmatch'
1 Answers

The solution to this question is to use Regex in extract function for exact match pattern.

pat_data = {'name': ['^aa$', 'bb', 'cc']}
df_p = pd.DataFrame(pat_data) 
print(df_p)

Adding the start and end string regex in pattern will make it look for exact string in same code without any other workaround.

Related