【发布时间】:2019-06-02 06:35:02
【问题描述】:
来自以下数据框:
d = {'col1':['a-1524112-124', 'b-1515', 'c-584854', 'a-15154']}
df = pd.DataFrame.from_dict(d)
我的最终目标是提取熊猫系列中的字母 a、b 或 c(作为字符串)。为此,我使用了re 模块中的.findall() 方法,如下所示:
# import the module
import re
# define the patterns
pat = 'a|b|c'
# extract the patterns from the elements in the specified column
df['col1'].str.findall(pat)
问题是输出,即每行中的字母 a、b 或 c,将出现在 list(单个元素)中,如下所示:
Out[301]:
0 [a]
1 [b]
2 [c]
3 [a]
虽然我希望将字母 a、b 或 c 作为字符串,如下所示:
0 a
1 b
2 c
3 a
我知道如果我将re.search() 与.group() 结合起来,我可以得到一个字符串,但如果我这样做了:
df['col1'].str.search(pat).group()
我将收到以下错误消息:
AttributeError: 'StringMethods' object has no attribute 'search'
使用.str.split() 不会完成这项工作,因为在我的原始数据帧中,我想捕获可能包含分隔符的字符串(例如,我可能想捕获a-b)
有没有人知道一个简单的解决方案,也许可以避免迭代操作,例如 for 循环或列表理解?
【问题讨论】:
标签: regex python-3.x pandas series