Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...