首页 > 解决方案 > 将多列的所有值设置为无

问题描述

我正在设置一个 Spark 批处理,旨在过滤掉一些需要清理的字段。如何将所有行的相关列的值设置为 None ?(我已经有一个只包含我想要更改的行的数据框)

我远不是 Spark 的专家,在问这里之前我搜索了很多,但我仍然无法找到一个足够简单的答案。

大约有 50 列,我无法硬编码列索引来访问它,因为它可能会在未来的批次中发生变化。

示例输入数据框(目标列包含数据):

id        TARGET 1       TARGET 2       TARGET 3     Col6     ...
someid1   Some(String)   Some(String)   Some(String) val1     ...
someid2   Some(String)   Some(String)   None         val4     ...
someid5   Some(String)   Some(String)   Some(String) val3     ...
someid6   Some(String)   Some(String)   Some(String) val7     ... 

预期输出数据框(所有目标列设置为无):

id        TARGET 1       TARGET 2       TARGET 3     Col6     ...
someid1   None           None           None         val1     ...
someid2   None           None           None         val4     ...
someid5   None           None           None         val3     ...
someid6   None           None           None         val7     ...

标签: scaladataframeapache-spark

解决方案


AFAIK,Spark 不接受 None 值。一个可能的解决方案是用转换为 String 的空值替换它们:

ds.
  .withColumn("target1", lit(null).cast(StringType))
  .withColumn("target2", lit(null).cast(StringType))

它产生以下输出:

+--------------------+-------+-------+-----+
|                  id|target1|target2| col6|
+--------------------+-------+-------+-----+
| 4201735573065099460|   null|   null|疦薠紀趣餅|
|-6432819446886055080|   null|   null|┵િ塇駢뱪|
|-7700306868339925800|   null|   null|鵎썢鳝踽嬌|
|-4913818084582557950|   null|   null|ꢵ痩찢쑖|
| 6731176796531697018|   null|   null|少⽬ᩢゖ謹|
+--------------------+-------+-------+-----+
only showing top 5 rows

root
 |-- id: long (nullable = false)
 |-- target1: string (nullable = true)
 |-- target2: string (nullable = true)
 |-- col6: string (nullable = true)

这也是您None在数据集中设置值时得到的结果。

case class TestData(id: Long, target1: Option[String], target2: Option[String], col6: String)

val res = Seq(
  TestData(1, Some("a"), Some("b"), "c"),
  TestData(2, Some("a"), Some("b"), "c"),
  TestData(3, Some("a"), Some("b"), "c"),
  TestData(4, Some("a"), Some("b"), "c")
).toDS()

res.show(5)
res.map(_.copy(target1 = None, target2 = None)).show(5)
res.printSchema()

将返回:

+---+-------+-------+----+
| id|target1|target2|col6|
+---+-------+-------+----+
|  1|      a|      b|   c|
|  2|      a|      b|   c|
|  3|      a|      b|   c|
|  4|      a|      b|   c|
+---+-------+-------+----+

+---+-------+-------+----+
| id|target1|target2|col6|
+---+-------+-------+----+
|  1|   null|   null|   c|
|  2|   null|   null|   c|
|  3|   null|   null|   c|
|  4|   null|   null|   c|
+---+-------+-------+----+

root
 |-- id: long (nullable = false)
 |-- target1: string (nullable = true)
 |-- target2: string (nullable = true)
 |-- col6: string (nullable = true)


推荐阅读