1

I have a dataframe and want to add a column of type String with null values. How can it be done using Spark Java API.

I used lit functions, but getting error when tried writing the DF and saveAsTable.

0

2 Answers 2

5
df.withColumn("col_name", lit(null).cast("string"))

or

import org.apache.spark.sql.types.StringType

df.withColumn("col_name", lit(null).cast(StringType))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for year answer; could maybe elaborate a bit more on why this resolves the question?
4

Was able to solve by using lit function on the column with null value and type cast the column to String type.

df.withColumn(
 "col_name", functions.lit(null)
).withColumn("col_name", 
  df.col("channel_name").cast(DataTypes.StringType)
)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.