python - Adding a nullable column in PySpark dataframe
问题描述
In Spark, literal columns, when added, are not nullable:
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.getOrCreate()
df = spark.createDataFrame([(1,)], ['c1'])
df = df.withColumn('c2', F.lit('a'))
df.printSchema()
# root
# |-- c1: long (nullable = true)
# |-- c2: string (nullable = false)
How to create a nullable column?
解决方案
The shortest method I've found - using when
(the otherwise
clause seems not needed):
df = df.withColumn('c2', F.when(F.lit(1).isNotNull(), F.lit('a')))
Full test result:
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.getOrCreate()
df = spark.createDataFrame([(1,)], ['c1'])
df = df.withColumn('c2', F.when(F.lit(1).isNotNull(), F.lit('a')))
df.show()
# +---+---+
# | c1| c2|
# +---+---+
# | 1| a|
# +---+---+
df.printSchema()
# root
# |-- c1: long (nullable = true)
# |-- c2: string (nullable = true)
推荐阅读
- c++ - OpenGL - 两个不同的元素数组缓冲区
- swift - 由于 texture.getbytes 功能,金属视图的记录很慢 - Swift
- python - Jupyter Notebook 在浏览器中运行良好,但在 Visual Studio 中运行良好
- javascript - 带有电子邮件和密码的firebase身份验证不起作用
- angular - Karma 没有运行任何服务测试,只有组件
- java - 当 previous.equals(" ") 时停止列表迭代器打印上一个
- ios - Swift 中的顶栏
- php - 如何在 axios react js 中设置 url?
- python - 使用 python paramiko 包获取路由器日志
- python - 如何将我的 python 应用程序制作/转换为 Rshiny 应用程序?它是一个脑筋急转弯!无法在 R 中找到 UI 需要的更改