Copy text between parentheses in pandas DataFrame column into another column

Question:

I am trying to copy text that appears between parentheses in a pandas DataFrame column into another column. I have come across this solution to parse strings accordingly: Regular expression to return text between parenthesis

I would like to assign the result element-by-element to the same row in a new column.
However, this doesn’t carry over directly to pandas Series. I seems that map/apply/lambda seems the way to go. I’ve arrived at this piece of code, but getting an invalid syntax error.

dataSources.dataUnits = dataSources.dataDescription.map(str.find("(")+1:str.find(")"))

Obviously, I’m not yet fluent enough there – help much appreciated.

Asked By: Stefan

||

Answers:

You can just use an apply with the same method suggested there:

In [11]: s = pd.Series(['hi(pandas)there'])

In [12]: s
Out[12]:
0    hi(pandas)there
dtype: object

In [13]: s.apply(lambda st: st[st.find("(")+1:st.find(")")])
Out[13]:
0    pandas
dtype: object

Or perhaps you could use one of the Series string methods e.g. replace:

In [14]: s.str.replace(r'[^(]*(|)[^)]*', '')
Out[14]:
0    pandas
dtype: object

throw away all the stuff before the ( and all the stuff after ) inclusive.

From 0.13 you can use the extract method:

In [15]: s.str.extract('.*((.*)).*')
Out[15]: 
0    pandas
dtype: object
Answered By: Andy Hayden
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.