向Spark DataFrame添加一个空列

arc*_*nic 26 python dataframe apache-spark apache-spark-sql pyspark

如在Web上的许多 其他位置所述,向现有DataFrame添加新列并不简单.不幸的是,拥有此功能非常重要(即使它在分布式环境中效率低下),尤其是在尝试连接两个DataFrames时unionAll.

null列添加到a DataFrame以便于实现最优雅的解决方法是unionAll什么?

我的版本是这样的:

from pyspark.sql.types import StringType
from pyspark.sql.functions import UserDefinedFunction
to_none = UserDefinedFunction(lambda x: None, StringType())
new_df = old_df.withColumn('new_column', to_none(df_old['any_col_from_old']))
Run Code Online (Sandbox Code Playgroud)

zer*_*323 59

你需要的只是文字和演员:

from pyspark.sql.functions import lit

new_df = old_df.withColumn('new_column', lit(None).cast(StringType()))
Run Code Online (Sandbox Code Playgroud)

一个完整的例子:

df = sc.parallelize([row(1, "2"), row(2, "3")]).toDF()
df.printSchema()

## root
##  |-- foo: long (nullable = true)
##  |-- bar: string (nullable = true)

new_df = df.withColumn('new_column', lit(None).cast(StringType()))
new_df.printSchema()

## root
##  |-- foo: long (nullable = true)
##  |-- bar: string (nullable = true)
##  |-- new_column: string (nullable = true)

new_df.show()

## +---+---+----------+
## |foo|bar|new_column|
## +---+---+----------+
## |  1|  2|      null|
## |  2|  3|      null|
## +---+---+----------+
Run Code Online (Sandbox Code Playgroud)

可以在此处找到Scala等效项:使用空/空字段值创建新的Dataframe


Zyg*_*ygD 6

选项不带import StringType

df = df.withColumn('foo', F.lit(None).cast('string'))
Run Code Online (Sandbox Code Playgroud)

完整示例:

from pyspark.sql import functions as F
df = spark.range(1, 3).toDF('c')

df = df.withColumn('foo', F.lit(None).cast('string'))

df.printSchema()
#     root
#      |-- c: long (nullable = false)
#      |-- foo: string (nullable = true)

df.show()
#     +---+----+
#     |  c| foo|
#     +---+----+
#     |  1|null|
#     |  2|null|
#     +---+----+
Run Code Online (Sandbox Code Playgroud)


Shr*_*bhu 5

我会将 lit(None) 转换为 NullType 而不是 StringType。因此,如果我们必须过滤掉该列上的非空行...可以按如下方式轻松完成

df = sc.parallelize([Row(1, "2"), Row(2, "3")]).toDF()

new_df = df.withColumn('new_column', lit(None).cast(NullType()))

new_df.printSchema() 

df_null = new_df.filter(col("new_column").isNull()).show()
df_non_null = new_df.filter(col("new_column").isNotNull()).show()
Run Code Online (Sandbox Code Playgroud)

如果您要强制转换为 StringType,请注意不要使用 lit("None")(带引号),因为它会无法在 col("new_column") 上搜索具有过滤条件 .isNull() 的记录。

  • 错误:`Parquet 数据源不支持 null 数据类型。;`。`StringType()` 有效。 (2认同)