Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy text between parentheses in pandas DataFrame column into another column

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.

like image 223
Stefan Avatar asked May 30 '13 17:05

Stefan


People also ask

How do I split a string into another column in pandas?

Pass expand=True to split strings into separate columns. Note that it is False by default. Use the parameter n to pass the number of splits you want. It is -1 by default to split by all the instances of the delimiter.

How do you get a string between brackets in Python?

Use re.search() to get a part of a string between two brackets. Call re.search(pattern, string) with the pattern r"\[([A-Za-z0-9_]+)\]" to extract the part of the string between two brackets.

How do you get between values in pandas?

Pandas Series: between() function The between() function is used to get boolean Series equivalent to left <= series <= right. This function returns a boolean vector containing True wherever the corresponding Series element is between the boundary values left and right.

How do I copy a DataFrame column to another data frame?

Using DataFrame. Pandas. DataFrame. copy() function returns a copy of the DataFrame. Select the columns from the original DataFrame and copy it to create a new DataFrame using copy() function.


1 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
like image 95
Andy Hayden Avatar answered Nov 13 '22 18:11

Andy Hayden