将pandas DataFrame列中括号之间的文本复制到另一列中 [英] Copy text between parentheses in pandas DataFrame column into another column
问题描述
我正在尝试将出现在pandas DataFrame列中括号之间的文本复制到另一列中.我遇到过这种解决方案,可以相应地解析字符串:使用正则表达式在括号之间返回文本
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
我想将结果按元素分配给新列中的同一行. 但是,这不会直接延续到熊猫系列.我似乎map/apply/lambda似乎是要走的路.我到了这段代码,但是收到了无效的语法错误.
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.
推荐答案
您可以使用与建议的相同方法进行申请那里:
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
或者也许您可以使用Series字符串方法之一,例如 replace
:
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.
从0.13开始,您可以使用提取方法:
From 0.13 you can use the extract method:
In [15]: s.str.extract('.*\((.*)\).*')
Out[15]:
0 pandas
dtype: object
这篇关于将pandas DataFrame列中括号之间的文本复制到另一列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!