我想创建一个时间戳列,以分别从包含月份和年份的两列创建折线图。 df看起来像这样: 我知道我可以创建一个字符串concat,然后将其转换为datetime列:
df.select('*',
concat('01', df['month'],
df['year']).alias('date')).withColumn("date",
df['date'].cast(TimestampType()))
但是我想要使用内置的PySpark功能的一种更清洁的方法,该功能还可以帮助我创建其他日期部分,例如星期数,季度等。有什么建议吗?
答案 0 :(得分:0)
您必须将字符串连接一次,创建timestamp
类型的列,然后可以轻松提取week
,quarter
等。
您可以使用此功能(并对其进行编辑以创建您需要的其他任何列):
def spark_date_parsing(df, date_column, date_format):
"""
Parses the date column given the date format in a spark dataframe
NOTE: This is a Pyspark implementation
Parameters
----------
:param df: Spark dataframe having a date column
:param date_column: Name of the date column
:param date_format: Simple Date Format (Java-style) of the dates in the date column
Returns
-------
:return: A spark dataframe with a parsed date column
"""
df = df.withColumn(date_column, F.to_timestamp(F.col(date_column), date_format))
# Spark returns 'null' if the parsing fails, so first check the count of null values
# If parse_fail_count = 0, return parsed column else raise error
parse_fail_count = df.select(
([F.count(F.when(F.col(date_column).isNull(), date_column))])
).collect()[0][0]
if parse_fail_count == 0:
return df
else:
raise ValueError(
f"Incorrect date format '{date_format}' for date column '{date_column}'"
)
用法(无论您使用什么日期格式):
df = spark_date_parsing(df, "date", "dd/MM/yyyy")