pyspark-从日期列创建一个列作为季度

tyg4sfes  于 2021-05-16  发布在  Spark
关注(0)|答案(1)|浏览(568)

我有一个这样的Dataframe,和列的格式 dateyyyy-mm-dd :

+--------+----------+---------+----------+-----------+--------------------+
|order_id|product_id|seller_id|      date|pieces_sold|       bill_raw_text|
+--------+----------+---------+----------+-----------+--------------------+
|     668|    886059|     3205|2015-01-14|         91|pbdbzvpqzqvtzxone...|
|    6608|    541277|     1917|2012-09-02|         44|cjucgejlqnmfpfcmg...|
|   12962|    613131|     2407|2016-08-26|         90|cgqhggsjmrgkrfevc...|
|   14223|    774215|     1196|2010-03-04|         46|btujmkfntccaewurg...|
|   15131|    769255|     1546|2018-11-28|         13|mrfsamfuhpgyfjgki...|
+--------+----------+---------+----------+-----------+--------------------+

我想创建一个列并将其附加到这个数据框中,该列包含字母q、季度、下划线、年份from date列。以下是我尝试过的:

from pyspark.sql import functions as F
sales_table.select(
    ("Q"+F.quarter('date')+"_"+F.date_format("date", "y")).alias('quarter_year')
).show(5)

这就是我得到的:

+------------+
|quarter_year|
+------------+
|        null|
|        null|
|        null|
|        null|
|        null|
+------------+

我的预期产出:

+---------------+
|   quarter_year|
+---------------+
|        Q1_2015|
|        Q3_2012|
|        Q3_2016|
|        Q1_2010|
|        Q4_2018|
+---------------+

我对没有错误消息和带有空值的列感到惊讶。我如何创建这个?

w6mmgewl

w6mmgewl1#

你不能 + 字符串列。你需要使用 concat . 你还需要使用 F.lit 对于用户指定字符串的文本列。
我认为这是一个错误-应该是 F.year('date') ? 不是 F.quarter('year') ?

sales_table.select(
    F.concat(F.lit("Q"), F.quarter('date'), F.lit("_"), F.year('date')).alias('quarter_year')
).show(5)

相关问题