从数据框中的字符串中提取第一个日期 [英] Extract first date from string in a data frame

查看:221
本文介绍了从数据框中的字符串中提取第一个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从数据框(Pandas)中提取格式为yyyy-mm-dd的第一个日期。当没有找到日期时,只返回一个空字符串。
这些是存储在数据帧中的数据的一些例子。

I want to extract the first date in format yyyy-mm-dd from a dataframe (Pandas). When no date is found, just return an empty string. These are some example of the data stored in the dataframe.

1976-05-17 [ ]
[ ] 1976-05-172 
1976-05-17       
1976-05-17 Atlanta, Georgia U.S.  
1976-05-17 1975-07-11
( 1976-05-17 ) 1976-05-17 (age 38) [ ]

在所有情况下,我想要 1976-05-17 或一个空字符串

In all cases I want 1976-05-17 or an empty string.

结果将在DataFrame上运行正则表达式,并将结果添加到新列

The result would be running a regular expression on a DataFrame and add the result to a new column

推荐答案

要获得第一个使用搜索,将停在第一个匹配的子串:

To get the first use search which will stop at the first matched substring:

 r = re.compile("\d{4}-\d{2}-\d{2}")

使用您的示例:

lines = """1976-05-17 [ ]
[ ] 1976-05-172
1976-05-17
1976-05-17 Atlanta, Georgia U.S.
1976-05-17 1975-07-11
( 1976-05-17 ) 1976-05-17 (age 38) [ ]"""
r = re.compile("\d{4}-\d{2}-\d{2}")
for line in lines.splitlines():
    m = r.search(line)
    if m:
        print(m.group())

输出:

1976-05-17
1976-05-17
1976-05-17
1976-05-17
1976-05-17
1976-05-17

如果您将其应用于df,则可以测试匹配是否匹配,否则使用空字符串作为值,即

If you are applying it to a df, you can test if there is a match if so use the match or else use an empty string as the value i.e.

import pandas as pd

df = pd.read_csv("test.txt")
print(df)
def match(x):
    m = r.search(x)
    if m:
        return  m.group()
    return  ""

输出:

print(df)
print df["date"].apply(match)

                                     date
0                          1976-05-17 [ ]
1                         [ ] 1976-05-172
2                              1976-05-17
3        1976-05-17 Atlanta, Georgia U.S.
4                   1976-05-17 1975-07-11
5  ( 1976-05-17 ) 1976-05-17 (age 38) [ ]


0    1976-05-17
1    1976-05-17
2    1976-05-17
3    1976-05-17
4    1976-05-17
5    1976-05-17
Name: date, dtype: object

您还可以将列设置为等于 str的返回值。提取如果你与南非的比赛没有关系:

You could also set the column equal to the return value of str.extract if you were ok with Nan for non matches:

print df["date"].str.extract(r"(\d{4}-\d{2}-\d{2})")

foo添加到列:

0    1976-05-17
1    1976-05-17
2    1976-05-17
3    1976-05-17
4    1976-05-17
5    1976-05-17
6           NaN
Name: date, dtype: object

这篇关于从数据框中的字符串中提取第一个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆