0

I have a df as follows:

name  date  

x     2020-07-20
y     2020-02-13
z     2020-01-21

I need a new column with the corresponding quarter as an integer, e.g.

name   date         quarter

x      2020-07-20   3
y      2020-02-13   1 
z      2020-01-21   1

I have defined my quarters as a list of strings so I thought I could use .withColumn + when col('date') in quarter range but get an error saying I cannot convert column to boolean.

1 Answer 1

2

You can use quarter function to extract it as an integer.

from pyspark.sql.functions import *

df1=spark.createDataFrame([("x","2020-07-20"),("y","2020-02-13"),("z","2020-01-21")], ["name", "date"])
df1.show()
+----+----------+
|name|      date|
+----+----------+
|   x|2020-07-20|
|   y|2020-02-13|
|   z|2020-01-21|
+----+----------+

df1.withColumn("quarter", quarter(col("date"))).show()

+----+----------+-------+
|name|      date|quarter|
+----+----------+-------+
|   x|2020-07-20|      3|
|   y|2020-02-13|      1|
|   z|2020-01-21|      1|
+----+----------+-------+
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.