복붙노트

[SCALA] 빈 / 널 필드 값 새로운 Dataframe 만들기

SCALA

빈 / 널 필드 값 새로운 Dataframe 만들기

나는이 새로운 DF에 (코드 아래에 "필드 1") 새 열을 추가 할 기존 dataframe하지만, 필요에서 새 Dataframe을 만드는 오전. 어떻게 그렇게 할 수 있습니까? 샘플 코드 예제 작업하는 것은 이해할 수있을 것이다.

val edwDf = omniDataFrame 
  .withColumn("field1", callUDF((value: String) => None)) 
  .withColumn("field2",
    callUdf("devicetypeUDF", (omniDataFrame.col("some_field_in_old_df")))) 

edwDf
  .select("field1", "field2")
  .save("odsoutdatafldr", "com.databricks.spark.csv"); 

해결법

  1. ==============================

    1.불 (널)을 사용할 수 있습니다 :

    불 (널)을 사용할 수 있습니다 :

    import org.apache.spark.sql.functions.{lit, udf}
    
    case class Record(foo: Int, bar: String)
    val df = Seq(Record(1, "foo"), Record(2, "bar")).toDF
    
    val dfWithFoobar = df.withColumn("foobar", lit(null: String))
    

    여기에 한 가지 문제는 열 유형이 null 인 것입니다 :

    scala> dfWithFoobar.printSchema
    root
     |-- foo: integer (nullable = false)
     |-- bar: string (nullable = true)
     |-- foobar: null (nullable = true)
    

    그리고는 CSV 작가에 의해 유지되지 않습니다. 이 하드 요구 사항 인 경우 당신도 데이터 유형 (문자열을 말할 수) 특정 유형에 열을 캐스팅 할 수 있습니다

    import org.apache.spark.sql.types.StringType
    
    df.withColumn("foobar", lit(null).cast(StringType))
    

    또는 문자열 설명

    df.withColumn("foobar", lit(null).cast("string"))
    

    또는이 같은 UDF를 사용합니다 :

    val getNull = udf(() => None: Option[String]) // Or some other type
    
    df.withColumn("foobar", getNull()).printSchema
    root
     |-- foo: integer (nullable = false)
     |-- bar: string (nullable = true)
     |-- foobar: string (nullable = true)
    

    파이썬 상당 여기에서 찾을 수 있습니다 : DataFrame를 촉발 빈 열 추가

  2. from https://stackoverflow.com/questions/32067467/create-new-dataframe-with-empty-null-field-values by cc-by-sa and MIT license