【发布时间】:2015-02-02 16:32:45
【问题描述】:
给定一个简单的 Pandas 系列,其中包含一些可以由多个句子组成的字符串:
In:
import pandas as pd
s = pd.Series(['This is a long text. It has multiple sentences.','Do you see? More than one sentence!','This one has only one sentence though.'])
Out:
0 This is a long text. It has multiple sentences.
1 Do you see? More than one sentence!
2 This one has only one sentence though.
dtype: object
我使用 pandas 字符串方法 split 和正则表达式模式将每一行拆分为单个句子(这会产生不必要的空列表元素 - 有关如何改进正则表达式的任何建议?)。
In:
s = s.str.split(r'([A-Z][^\.!?]*[\.!?])')
Out:
0 [, This is a long text., , It has multiple se...
1 [, Do you see?, , More than one sentence!, ]
2 [, This one has only one sentence though., ]
dtype: object
这会将每一行转换为字符串列表,每个元素包含一个句子。
现在,我的目标是使用字符串方法contains 分别检查每一行中的每个元素以匹配特定的正则表达式模式并相应地创建一个新的系列来存储返回的布尔值,每个都表示正则表达式是否匹配至少有一个列表元素。
我希望是这样的:
In:
s.str.contains('you')
Out:
0 False
1 True
2 False
'you',但第 1 行包含,而第 2 行不包含。
但是,当执行上述操作时,返回是
0 NaN
1 NaN
2 NaN
dtype: float64
我还尝试了一个不起作用的列表理解:
result = [[x.str.contains('you') for x in y] for y in s]
AttributeError: 'str' object has no attribute 'str'
关于如何实现这一点的任何建议?
【问题讨论】:
标签: python regex string pandas