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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With