创建空/空字段值新的数据框 [英] Create new Dataframe with empty/null field values
本文介绍了创建空/空字段值新的数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建从现有的数据帧新的数据框,但需要(在下面code字段1),在这个新的DF添加新列。我该怎么办呢?工作示例code例子将是AP preciated。
VAL edwDf = omniDataFrame
.withColumn(字段1,callUDF((价值:字符串)=>无))
.withColumn(字段2
callUdf(devicetypeUDF,(omniDataFrame.col(some_field_in_old_df))))edwDf
。选择(字段1,字段2)
.save(odsoutdatafldr,com.databricks.spark.csv);
解决方案
有可能使用亮起(空)
:
进口org.apache.spark.sql.functions {点亮,UDF}案例类记录(富:智力,酒吧:字符串)
VAL DF = sqlContext.createDataFrame(记录(1,富)::记录(2,巴)::无)VAL dfWithFoobar = df.withColumn(FOOBAR,点燃(空:字符串))
这里的一个问题是,列类型为空
:
斯卡拉> dfWithFoobar.printSchema
根
| - 富:整数(可为空= FALSE)
| - 条:字符串(可为空=真)
| - foobar的:空(可为空=真)
和它不是由CSV作家保留。如果它是一个硬性要求,你可以投栏的具体类型(可以说字符串):
进口org.apache.spark.sql.types.StringType
df.withColumn(FOOBAR,点燃(空:字符串).cast(StringType))
或使用UDF这样的:
VAL getNull = UDF(()=>无:选项[字符串])//或一些其他类型df.withColumn(FOOBAR,getNull())。printSchema
根
| - 富:整数(可为空= FALSE)
| - 条:字符串(可为空=真)
| - foobar的:字符串(可为空=真)
I am creating a new Dataframe from an existing dataframe, but need to add new column ("field1" in below code) in this new DF. How do I do so? Working sample code example will be appreciated.
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");
解决方案
It is possible to use lit(null)
:
import org.apache.spark.sql.functions.{lit, udf}
case class Record(foo: Int, bar: String)
val df = sqlContext.createDataFrame(Record(1, "foo") :: Record(2, "bar") :: Nil)
val dfWithFoobar = df.withColumn("foobar", lit(null: String))
One problem here is that the column type is null
:
scala> dfWithFoobar.printSchema
root
|-- foo: integer (nullable = false)
|-- bar: string (nullable = true)
|-- foobar: null (nullable = true)
and it is not retained by the csv writer. If it is a hard requirement you can cast column to the specific type (lets say String):
import org.apache.spark.sql.types.StringType
df.withColumn("foobar", lit(null: String).cast(StringType))
or use an UDF like this:
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)
这篇关于创建空/空字段值新的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文