python - 如何对 Pandas RE .str.extract() 使用 RE OR 操作数

我是新手,我确信这在我的代码中有些愚蠢。在我的辩护中,我尝试重新阅读 Python RE 文档 here在询问和搜索之前,但到目前为止没有看到重复的问题(这让我感到惊讶。)

在 DataFrame 之外,我在这里有重新工作的示例:

x = 'my best friend's birthday is 24 Jan 2001.'
print(re.findall('\d{1,2}\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s\d{2,4}', x))
<Anaconda console returns:> 24 Jan 2001

但是在我的 Dataframe (df1) 中我有以下内容:

index     text
0         My birthday is 2/21/19
1         Your birthday is 4/1/20
2         my best friend's birthday is 24 Jan 2001.   

当我运行以下代码时:

df1['dates'] = df1['text'].str.extract('.*?(\d+[/-]\d+[/-]?\d*).*?|\d{1,2}\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s\d+')
print('df1['dates'])

我得到以下结果:

     dates
0    2/21/19
1    4/1/20
2    NaN

我曾尝试使用括号、重新阅读文档以及其他一些导致无休止错误的调整。我确定这是一个明显的错误,但我没有看到。有人可以帮忙吗?谢谢。

最佳答案

在 pandas 中使用 .extract() 时,您必须有一个捕获组。您在 OR 之前的捕获组 | 正在查找带斜线的日期。但是在 OR 之后,您只有一个非捕获组。

这里我在整个搜索模式周围放置了一个捕获,并且 OR 的每一侧也有一个非捕获组。

import pandas as pd

df = pd.DataFrame({'text': ['My birthday is 2/21/19', 
    'Your birthday is 4/1/20', 
    'my best friend\'s birthday is 24 Jan 2001.']})

df.text.str.extract(
    r'((:?\d+[/-]\d+[/-]?\d*)|' + 
    r'(:?\d{1,2}\s(:?Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s\d+))', 
    expand=False)[0]

# returns:
0        2/21/19
1         4/1/20
2    24 Jan 2001

https://stackoverflow.com/questions/49254224/

相关文章:

python - 如何使用 R 按列将 .csv 拆分为多个 .csv?

amazon-web-services - 在 Looker 中可以进行分页吗?

asynchronous - 使用 async/await 进行异步 mocha 测试时遇到问题

google-apps - 迄今为止的 Google 表格查询字符串

excel-formula - 在单元格中使用逗号分隔值作为下拉选项[Excel 2013]

tensorflow - 如何在 Estimator 之外使用 tensorflow.feature

c# - 可空类型 "int?"(包括问号)的默认值是多少?

python - LineString 和 Point 之间的距离

jenkins - 如何在多分支管道项目中为每个分支级别的用户提供访问权限?

android - React Native StackNavigator 在重新进入时消失