将 Pandas DataFrame 列中括号之间的文本复制到另一列中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16842001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copy text between parentheses in pandas DataFrame column into another column
提问by Stefan
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
我正在尝试将出现在 Pandas DataFrame 列中括号之间的文本复制到另一列中。我遇到了这个解决方案来相应地解析字符串:Regular expression to return text between parentheses
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.
我想将结果逐个元素分配给新列中的同一行。但是,这不会直接延续到Pandas系列。我似乎 map/apply/lambda 似乎是要走的路。我已经到达了这段代码,但收到了无效的语法错误。
dataSources.dataUnits = dataSources.dataDescription.map(str.find("(")+1:str.find(")"))
Obviously, I'm not yet fluent enough there - help much appreciated.
显然,我在那里还不够流利 - 非常感谢帮助。
回答by Andy Hayden
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:
或者,也许您可以使用系列字符串方法之一,例如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 extractmethod:
从 0.13 开始,您可以使用提取方法:
In [15]: s.str.extract('.*\((.*)\).*')
Out[15]:
0 pandas
dtype: object

