0
我在PySpark中有一个数据框。我想有条件地在数据框中添加一列。在Pyspark中有条件添加列到数据框
说如果数据框没有列,则添加一个包含null
值的列。 如果列存在,则什么也不做,返回相同的数据帧作为新的数据帧
我如何通过条件语句中PySpark
我在PySpark中有一个数据框。我想有条件地在数据框中添加一列。在Pyspark中有条件添加列到数据框
说如果数据框没有列,则添加一个包含null
值的列。 如果列存在,则什么也不做,返回相同的数据帧作为新的数据帧
我如何通过条件语句中PySpark
它并不难,但你需要一个多一点比列名称做正确的。需要进口
from pyspark.sql import types as t
from pyspark.sql.functions import lit
from pyspark.sql import DataFrame
实施例的数据:
df = sc.parallelize([("a", 1, [1, 2, 3])]).toDF(["x", "y", "z"])
一个辅助功能(与旧版本的Python使用剥离型注释):
def add_if_not_present(df: DataFrame, name: str, dtype: t.DataType) -> DataFrame:
return (df if name in df.columns
else df.withColumn(name, lit(None).cast(dtype)))
实例:
add_if_not_present(df, "foo", t.IntegerType())
DataFrame[x: string, y: bigint, z: array<bigint>, foo: int]
add_if_not_present(df, "x", t.IntegerType())
DataFrame[x: string, y: bigint, z: array<bigint>]
DataFrame[x: string, y: bigint, z: array<bigint>, foobar: struct<foo:int,bar:int>]