Pyspark使用withColumn将派生列添加到数据框

时间:2017-05-25 14:23:39

标签: pyspark

我目前有一个具有以下架构的数据框;

Year: integer (nullable = true)
Month: integer (nullable = true)
Day: integer (nullable = true)
Hour: integer (nullable = true)
Minute: integer (nullable = true)
Second: integer (nullable = true)

我想基本上向我的数据框添加一个额外的列,该列使用上述日期组件来构造日期时间类型列。我目前正在尝试使用以下内容;

df = df.withColumn("DeptDateTime",getDate(df['Year'], df['Month'], df['Day'], df['Hour'], df['Minute'], df['Second']))

我正在努力编写函数getDate,因为我想查看Year的长度(目前是整数)&如果它是2位数(即16位),那么前缀" 20"制作" 2016"需要对每个日期组件进行此操作,以便按以下格式构建日期时间:yyyy-mm-dd hh:mm:ss

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:0)

您可以使用datetime模块创建格式。 以下代码对我有用,

from datetime import datetime

def getdate(*args):
    dt_str = '-'.join(map(str,args[:3])) + ' ' +  ':'.join(map(str,args[3:]))
    yr_len = len(str(args[0]))
    if yr_len == 2:
       yr = 'y'
    else:
       yr = 'Y'
    formtd_date = datetime.strptime(dt_str,"%{}-%m-%d %H:%M:%S".format(yr)).strftime("%Y-%m-%d %H:%M:%S")
    return formtd_date

Test input :      
  1.getdate(16,1,2,4,5,6)
  2.getdate(2016,1,2,04,5,58)
output :
  1.2016-01-02 04:05:06
  2.2016-01-02 04:05:58

答案 1 :(得分:0)

转换为日期

首先,让我们创建一些样本数据集。

df_pd = pd.DataFrame([[16, 3, 15], 
                      [2016, 4, 3]], 
                     columns=['Year', 'Month', 'Day'])
df = spark.createDataFrame(df_pd)

然后你可以编写udf函数来解决你的问题。

from pyspark.sql import functions as func
from pyspark.sql.types import *

def get_date(year, month, day):
    year = str(year)
    month = str(month)
    day = str(day)
    if len(str(year)) == 2:
        year = '20' + year
    return year + '-' + month + '-' + day
udf_get_date = func.udf(get_date, returnType=StringType())

现在,我们可以将UDF功能应用于3列并再次使用.cast(DateType()),以便您拥有正确的格式

df = df.withColumn('date', udf_get_date('Year', 'Month', 'Day').cast(DateType()))

<强>输出

+----+-----+---+----------+
|Year|Month|Day|      date|
+----+-----+---+----------+
|  16|    3| 15|2016-03-15|
|2016|    4|  3|2016-04-03|
+----+-----+---+----------+

转换为日期时间格式

这非常相似,我在这里添加了一些变体,您也可以使用datetime

import pandas as pd
import datetime

df_pd = pd.DataFrame([[16, 3, 15, 10, 34, 14], 
                      [2016, 4, 3, 23, 8, 12]], 
                     columns=['Year', 'Month', 'Day', 'Hour', 'Minute', 'Second'])
df = spark.createDataFrame(df_pd)

def get_date(year, month, day, hour, minute, second):
    year = str(year)
    if len(str(year)) == 2:
        year = '20' + year
    return str(datetime.datetime(int(year), month, day, hour, minute, second))
udf_get_date = func.udf(get_date, returnType=StringType())
df = df.withColumn('date', udf_get_date('Year', 'Month', 'Day', 'Hour', 'Minute', 'Second').cast(TimestampType()))

<强>输出

+----+-----+---+----+------+------+--------------------+
|Year|Month|Day|Hour|Minute|Second|                date|
+----+-----+---+----+------+------+--------------------+
|  16|    3| 15|  10|    34|    14|2016-03-15 10:34:...|
|2016|    4|  3|  23|     8|    12|2016-04-03 23:08:...|
+----+-----+---+----+------+------+--------------------+
相关问题