Estimated reading time: 2 minutes
In Python, there are a number of re-occurring value errors that you will come across.
In this particular error it is usually related to when you are running regular expressions as part of a pattern search.
So how does the problem occur?
In the below, the aim of the code is to purely create a data frame, that can then be searchable.
To search the data frame we will use str.extract
import pandas as pd rawdata = [['Joe', 'Jim'], ['Jane', 'Jennifer'], ['Ann','Alison']] datavalue = pd.DataFrame(data=rawdata, columns=['A', 'B'])
We then add the below code to complete the extract of the string “Joe”.
a = datavalue['A'].str.extract('Joe') print(a)
But it gives the below error, what we are trying to solve for:
ValueError: pattern contains no capture groups Process finished with exit code 1
But why did the error occur , and how can we fix it?
In essence when you try to complete a str.extract, the value you are looking for should be enclosed in brackets i.e ()
In the above, it views ‘Joe’ as an incorrect value to be passed into the str.extract function, and returns the error.
So to fix this problem, we would change this line to:
a = datavalue['A'].str.extract('(Joe)')
As a result the program runs without error, and returns the below result:
0 0 Joe 1 NaN 2 NaN
The full corrected code to be used is then:
import pandas as pd rawdata = [['Joe', 'Jim'], ['Jane', 'Jennifer'], ['Ann','Alison']] datavalue = pd.DataFrame(data=rawdata, columns=['A', 'B']) a = datavalue['A'].str.extract('(Joe)') print(a)