简体   繁体   English

从混合字母和数字列 pandas 中提取日期时间

[英]Extracting date time from a mixed letter and numeric column pandas

I have a column in pandas dataframe that contains two types of information = 1. date and time, 2=company name.我在 pandas dataframe 中有一个列,其中包含两种类型的信息 = 1. 日期和时间,2=公司名称。 I have to split the column into two (date_time, full_company_name).我必须将列分成两列(date_time、full_company_name)。 Firstly I tried to split the columns based on character count (first 19 one column, the rest to other column) but then I realized that sometimes the date is missing so the split might not work.首先,我尝试根据字符数拆分列(前 19 个一列,rest 到另一列),但后来我意识到有时缺少日期,因此拆分可能不起作用。 Then I tried using regex but I cant seem to extract it correctly.然后我尝试使用正则表达式,但我似乎无法正确提取它。

The column:专栏:

在此处输入图像描述

the desired output:所需的 output:

在此处输入图像描述

If the dates are all properly formatted, maybe you don't have to use regex如果日期格式都正确,也许你不必使用正则表达式

df = pd.DataFrame({"A": ["2021-01-01 05:00:00Acme Industries",
                         "2021-01-01 06:00:00Acme LLC"]})
df["date"] = pd.to_datetime(df.A.str[:19])
df["company"] = df.A.str[19:]
df
#                                     A                 date          company
# 0  2021-01-01 05:00:00Acme Industries  2021-01-01 05:00:00  Acme Industries
# 1         2021-01-01 06:00:00Acme LLC  2021-01-01 06:00:00         Acme LLC

OR或者

df.A.str.extract("(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})(.*)")

Note: If you have an option to avoid concatenating those strings to begin with, please do so.注意:如果您可以选择避免连接这些字符串,请这样做。 This is not a healthy habit.这不是一个健康的习惯。

Solution (not that pretty gets the job done):解决方案(不是那么漂亮就可以完成工作):

import pandas as pd
from datetime import datetime
import re

df = pd.DataFrame()
# creating a list of companies
companies = ['Google', 'Apple', 'Microsoft', 'Facebook', 'Amazon', 'IBM', 
             'Oracle', 'Intel', 'Yahoo', 'Alphabet']
# creating a list of random datetime objects
dates = [datetime(year=2000 + i, month=1, day=1) for i in range(10)]
# creating the column named 'date_time/full_company_name'
df['date_time/full_company_name'] = [f'{str(dates[i])}{companies[i]}' for i in range(len(companies))]

# Before:
# date_time/full_company_name
# 2000-01-01 00:00:00Google
# 2001-01-01 00:00:00Apple
# 2002-01-01 00:00:00Microsoft
# 2003-01-01 00:00:00Facebook
# 2004-01-01 00:00:00Amazon
# 2005-01-01 00:00:00IBM
# 2006-01-01 00:00:00Oracle
# 2007-01-01 00:00:00Intel
# 2008-01-01 00:00:00Yahoo
# 2009-01-01 00:00:00Alphabet

new_rows = []
for row in df['date_time/full_company_name']:
    # extract the date_time from the row using regex
    date_time = re.search(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}', row)
    # handle case of empty date_time
    date_time = date_time.group() if date_time else ''
    # extract the company name from the row from where the date_time ends
    company_name = row[len(date_time):]
    # create a new row with the extracted date_time and company_name
    new_rows.append([date_time, company_name])

# drop the column 'date_time/full_company_name'
df = df.drop(columns=['date_time/full_company_name'])
# add the new columns to the dataframe: 'date_time' and 'company_name'
df['date_time'] = [row[0] for row in new_rows]
df['company_name'] = [row[1] for row in new_rows]

# After:
# date_time            full_company_name
# 2000-01-01 00:00:00       Google
# 2001-01-01 00:00:00       Apple
# 2002-01-01 00:00:00       Microsoft
# 2003-01-01 00:00:00       Facebook
# 2004-01-01 00:00:00       Amazon
# 2005-01-01 00:00:00       IBM
# 2006-01-01 00:00:00       Oracle
# 2007-01-01 00:00:00       Intel
# 2008-01-01 00:00:00       Yahoo
# 2009-01-01 00:00:00       Alphabet

use a non capturing group?.* instead of (.*)使用非捕获组?.* 而不是 (.*)

df = pd.DataFrame({"A": ["2021-01-01 05:00:00Acme Industries",
                         "2021-01-01 06:00:00Acme LLC"]})

df.A.str.extract("(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})?.*")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM