为少数列创建空值的dataframe

x8goxv8g  于 2021-07-09  发布在  Spark
关注(0)|答案(2)|浏览(510)

我想创造一个 DataFrame 使用 RDD .
首先我要创造一个 RDD 使用以下代码-

val account = sc.parallelize(Seq(
                                 (1, null, 2,"F"), 
                                 (2, 2, 4, "F"),
                                 (3, 3, 6, "N"),
                                 (4,null,8,"F")))

工作正常-
account:org.apache.spark.rdd.rdd[(int,any,int,string)]=parallelcollectionrdd[0]at parallelize at:27
但是当你试图创造 DataFrameRDD 使用以下代码

account.toDF("ACCT_ID", "M_CD", "C_CD","IND")

我在犯错误
java.lang.unsupportedoperationexception:不支持任何类型的架构
我分析过每当我把 null 价值 Seq 只有我错了。
有没有办法添加空值?

tvokkenx

tvokkenx1#

不使用RDD的替代方法:

import spark.implicits._

val df = spark.createDataFrame(Seq(
  (1, None,    2, "F"),
  (2, Some(2), 4, "F"),
  (3, Some(3), 6, "N"),
  (4, None,    8, "F")
)).toDF("ACCT_ID", "M_CD", "C_CD","IND")

df.show
+-------+----+----+---+
|ACCT_ID|M_CD|C_CD|IND|
+-------+----+----+---+
|      1|null|   2|  F|
|      2|   2|   4|  F|
|      3|   3|   6|  N|
|      4|null|   8|  F|
+-------+----+----+---+

df.printSchema
root
 |-- ACCT_ID: integer (nullable = false)
 |-- M_CD: integer (nullable = true)
 |-- C_CD: integer (nullable = false)
 |-- IND: string (nullable = true)
tjvv9vkg

tjvv9vkg2#

问题是,任何类型都太普通,spark根本不知道如何序列化它。在您的例子中,您应该显式地提供一些特定的类型 Integer . 因为在scala中不能将null赋给基元类型,所以可以使用 java.lang.Integer 相反。所以试试这个:

val account = sc.parallelize(Seq(
                                 (1, null.asInstanceOf[Integer], 2,"F"), 
                                 (2, new Integer(2), 4, "F"),
                                 (3, new Integer(3), 6, "N"),
                                 (4, null.asInstanceOf[Integer],8,"F")))

下面是一个输出:

rdd: org.apache.spark.rdd.RDD[(Int, Integer, Int, String)] = ParallelCollectionRDD[0] at parallelize at <console>:24

以及相应的Dataframe:

scala> val df = rdd.toDF("ACCT_ID", "M_CD", "C_CD","IND")

df: org.apache.spark.sql.DataFrame = [ACCT_ID: int, M_CD: int ... 2 more fields]

scala> df.show
+-------+----+----+---+
|ACCT_ID|M_CD|C_CD|IND|
+-------+----+----+---+
|      1|null|   2|  F|
|      2|   2|   4|  F|
|      3|   3|   6|  N|
|      4|null|   8|  F|
+-------+----+----+---+

您还可以考虑一些更简洁的方法来声明空整数值,如:

object Constants {
  val NullInteger: java.lang.Integer = null
}

相关问题