簡體   English   中英

DataFrame 包含一列具有以下類型的日期:“'5-15-2019'”和 05152021。我想提取它的模式

[英]DataFrame contains a column of dates which are having these types: "'5-15-2019'" and 05152021.I want to extract pattern of it

DataFrame 包含具有以下類型的日期:“21-10-2021”和 29052021。我想提取它的模式。 例如 '5-15-2019',它需要生成 '%d-%m-%Y' '05152021' 它需要生成 '%d%m%Y'

我這樣試過:

search6=[]
for val in list(df.apply(lambda x:re.search('(?:[1-9]|[12][0-9]|3[01])[-](?:[1-9]|10|11|12])[-]\d{2,4}',str(x)))):
if val:
li=val.group()
search6.append(li)
print(search6)

output:我得到了這些模式的列表。我需要獲取模式“%d-%m-%Y”,同樣我還需要獲取“%d%m%Y”的模式。我需要怎么做? 任何人都可以幫助我。謝謝

您可以使用內部 pandas 方法pandas._libs.tslibs.parsing.guess_datetime_format 請注意,這不是公共 API 的一部分,因此 function 將來可能會在沒有任何警告的情況下更改。

選項1
from pandas._libs.tslibs.parsing import guess_datetime_format
s = pd.Series(['21-10-2021', '29052021', '5-15-2019', '05152021', '20000101', '01-01-2001'])

s.map(lambda x: guess_datetime_format(x, dayfirst=True))
選項 2

....YYYY日期。 對於那些你需要通過臨時添加破折號來作弊的人:

def parse(x):
    out = guess_datetime_format(x, dayfirst=True)
    if out is None and x.isdigit() and len(x)==8:
        out = (guess_datetime_format(f'{x[:2]}-{x[2:4]}-{x[4:]}',
                                     dayfirst=True)
               .replace('-', '')
              )
    return out

s.map(parse)

例子:

         date   option1   option2
0  21-10-2021  %d-%m-%Y  %d-%m-%Y
1    29052021      None    %d%m%Y
2   5-15-2019  %m-%d-%Y  %m-%d-%Y
3    05152021      None    %m%d%Y
4    20000101    %Y%m%d    %Y%m%d
5  01-01-2001  %d-%m-%Y  %d-%m-%Y

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM