从 Pandas 列中的元素中提取文本,写入新列

use*_*901 6 python dataframe pandas

我在 Pandas DataFrame 的列 (COL_NAME) 中有一些数据。我想提取“(”和“)”之间的一些文本(该数据要么存在,要么括号根本不存在,尽管数据中可能有不止一组括号)。然后我想将括号中的数据写入另一列,然后从原始字符串中删除“(XXX)”。

IE

COL_NAME
========
(info) text (yay!)
I love text
Text is fun
(more info) more text
lotsa text (boo!)
Run Code Online (Sandbox Code Playgroud)

变成:

COL_NAME          NEW_COL
========          =======
text (yay!)       info
i love text       None
Text is fun       None
more text         more info
lots text (boo!)  None
Run Code Online (Sandbox Code Playgroud)

我可以通过隔离列、迭代其元素、拆分 (、创建两个新列表,然后将它们添加到 DataFrame 中来完成此操作,但肯定有一种更 Pythonic/Pandic 的方式来做到这一点,对吧?

谢谢!

jez*_*ael 7

目前尚不清楚为什么第二个括号不匹配。也许是因为 char !.

然后您可以使用extract与正则表达式。

正则表达式的\(([A-Za-z0-9 _]+)\)意思是:

  1. \(匹配文字(字符
  2. (开始一个新组
  3. [A-Za-z0-9 _]是匹配任何字母(大写或小写)、数字或下划线和空格的字符集
  4. +与前面的元素(字符集)匹配一次或多次。
  5. )结束小组
  6. \)匹配文字)字符

第二个括号不匹配,因为正则表达式排除字符!- 它不在括号中[A-Za-z0-9 _]

import pandas as pd
import numpy as np
import io

temp=u"""(info) text (yay!)
I love text
Text is fun
(more info) more text
lotsa text (boo!)"""

df = pd.read_csv(io.StringIO(temp), header=None, names=['original'])
print df
#                  original
#0       (info) text (yay!)
#1              I love text
#2              Text is fun
#3  (more info) more text
#4        lotsa text (boo!)

df['col1'] = df['original'].str.extract(r"\(([A-Za-z0-9 _]+)\)")
df['col2'] = df['original'].str.replace(r"\(([A-Za-z0-9 _]+)\)", "")
print df
#                original       col1               col2
#0     (info) text (yay!)       info        text (yay!)
#1            I love text        NaN        I love text
#2            Text is fun        NaN        Text is fun
#3  (more info) more text  more info          more text
#4      lotsa text (boo!)        NaN  lotsa text (boo!)
Run Code Online (Sandbox Code Playgroud)