【问题标题】:Python Spliting Date/Time into Month, Date, Year, Time columnsPython将日期时间拆分为月、日期、年、时间列
【发布时间】:2019-02-20 19:58:42
【问题描述】:

我有一个带有“日期/时间”列的数据框,如下所示:

import pandas as pd

example = {'Date/Time' : ['4/1/2014 0:11:00', '4/1/2014 0:17:00', '4/1/2014 0:21:00', '4/1/2014 0:28:00']}

df = pd.DataFrame(example)

我想要做的是将列拆分为 3 个不同的列(月、日期、年和时间)。

我尝试使用基于用于解决其他类似问题的代码的正则表达式,该问题是将包含“性别、电子邮件、电话号码”的列拆分为每个列。

# create gender, phone, email columns by splitting leader contact 
df3[['gender','phone','email']]=df3['Contact'].str.extract('\(([A-Z])\)\s?(\d{3}-\d{3}-\d{4})?\s?(.*)', expand = False)

我基本上试图操纵 extract() 部分。然而,这对我来说太难弄清楚了。我不介意使用正则表达式或其他“日期/时间”包。

如果有人能帮忙,对我的学习会有很大帮助。

【问题讨论】:

  • 转换为datetime 并获得不需要正则表达式的单个组件
  • 使用pd.to_datetime,然后使用.dt访问器

标签: python regex pandas date time


【解决方案1】:

我将发布最直接的方法

df['date'] = pd.to_datetime(df['Date/Time'])

df['month'], df['day'], df['year'], df['time'] = (
    df.date.dt.month, df.date.dt.day, df.date.dt.year, df.date.dt.time)


    Date/Time           date                month   day year    time
0   4/1/2014 0:11:00    2014-04-01 00:11:00 4       1   2014    00:11:00
1   4/1/2014 0:17:00    2014-04-01 00:17:00 4       1   2014    00:17:00
2   4/1/2014 0:21:00    2014-04-01 00:21:00 4       1   2014    00:21:00
3   4/1/2014 0:28:00    2014-04-01 00:28:00 4       1   2014    00:28:00

【讨论】:

    【解决方案2】:
    df.assign(**{ x: getattr(pd.to_datetime(df['Date/Time']).dt, x.lower()) for x in ['Month', 'Date', 'Year', 'Time']})
    
              Date/Time  Month        Date  Year      Time
    0  4/1/2014 0:11:00      4  2014-04-01  2014  00:11:00
    1  4/1/2014 0:17:00      4  2014-04-01  2014  00:17:00
    2  4/1/2014 0:21:00      4  2014-04-01  2014  00:21:00
    3  4/1/2014 0:28:00      4  2014-04-01  2014  00:28:00
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 2013-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多