从pandas DataFrame中的文本中提取子字符串作为新列

无腿

我有一个要在下面计算的“单词”列表

word_list = ['one','three']

我在pandas数据框中有一个专栏,下面有文字。

TEXT                                       |
-------------------------------------------|
"Perhaps she'll be the one for me."        |
"Is it two or one?"                        |
"Mayhaps it be three afterall..."          |
"Three times and it's a charm."            |
"One fish, two fish, red fish, blue fish." |
"There's only one cat in the hat."         |
"One does not simply code into pandas."    |
"Two nights later..."                      |
"Quoth the Raven... nevermore."            |

所需的输出如下所示,其中保留原始文本列,但仅将word_list中的单词提取到新列中

TEXT                                       | EXTRACT
-------------------------------------------|---------------
"Perhaps she'll be the one for me."        | one
"Is it two or one?"                        | one
"Mayhaps it be three afterall..."          | three
"Three times and it's a charm."            | three
"One fish, two fish, red fish, blue fish." | one
"There's only one cat in the hat."         | one
"One does not simply code into pandas."    | one
"Two nights later..."                      | 
"Quoth the Raven... nevermore."            |

有没有办法在Python 2.7中做到这一点?

cs95

用途str.extract

df['EXTRACT'] = df.TEXT.str.extract('({})'.format('|'.join(word_list)), 
                        flags=re.IGNORECASE, expand=False).str.lower().fillna('')
df['EXTRACT']

0      one
1      one
2    three
3    three
4      one
5      one
6      one
7         
8         
Name: EXTRACT, dtype: object

输入的每个单词word_list都由正则表达式分隔符连接|,然后传递给str.extract进行正则表达式模式匹配。

re.IGNORECASE为区分大小写的比较而打开了开关,并且将结果匹配项转换为小写形式以与您的预期输出匹配。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

从pandas dataframe列的字符串中提取数字

Python-使用正则表达式从Pandas DataFrame中的列(包含字符串)中提取权重并将其添加到新列中

从一列中提取以“ Unit”开头的字符串并将其复制到新列中:Pandas

从列表中的子字符串创建新的 pandas 列

Pandas Dataframe:从字符串中提取数值(包括小数)

使用正则表达式从pandas列中提取子字符串

从Pandas Dataframe列中提取字符串形式的JSON对象列表

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

从 Pandas DF 列中提取数据/字符串

从pandas的字符串datetime列中提取日期

从 Pandas DF 列中提取字符串

从Pandas中的字符串中提取int

从字符串列表中删除某些字符串作为 pandas.DataFrame 中的列

Pandas ,從列中的字符串值中提取日期

如何从 Pandas DataFrame 中提取子列?

如何在 Pandas 列中提取部分字符串並創建一個新列

在 Pandas df 列中的兩個子字符串之間提取字符串

在 Pandas 数据帧中提取字符串中两个字符之间的子字符串

在pandas df中提取带有子字符串的行,该子字符串包含空格

从 Pandas DataFrame 中的列中提取数据

如何在pandas数据框中的列的所有行中提取字符串中的大写单词?

使用python删除pandas DataFrame中的子字符串

如何从 Pandas 数据框中的字符串中正确提取子字符串?

pandas:在连字符之前或之后提取特定文本,以给定的子字符串结尾

如何将Pandas DataFrame中字典的字符串表示形式转换为新列?

使用 Regex 或 Pandas 从字符串中提取多个参数

如何使用Pandas从字符串中提取算术运算

蟒蛇。从Pandas列中提取字符串的最后一个字母

从 Pandas 的列中提取字符串和相对浮点数