2017-01-20 55 views
0

我在PySpark中有一個數據框。我想有條件地在數據框中添加一列。在Pyspark中有條件添加列到數據框

說如果數據框沒有列,則添加一個包含null值的列。 如果列存在,則什麼也不做,返回相同的數據幀作爲新的數據幀

我如何通過條件語句中PySpark

回答

1

它並不難,但你需要一個多一點比列名稱做正確的。需要進口

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>] 
相關問題