使用映射重命名和选择Apache Spark数据帧(Scala)上的列
从数据帧开始:使用映射重命名和选择Apache Spark数据帧(Scala)上的列,scala,apache-spark,apache-spark-sql,Scala,Apache Spark,Apache Spark Sql,从数据帧开始: val someDF = Seq( (8, "bat", "h"), (64, "mouse", "t"), (-27, "horse", "x") ).toDF("number", "thing", "letter") someDF.show() +------+-----+------+ |number|thing|letter| +------+-----+------+ | 8| bat| h| | 64|mouse| t|
val someDF = Seq(
(8, "bat", "h"),
(64, "mouse", "t"),
(-27, "horse", "x")
).toDF("number", "thing", "letter")
someDF.show()
+------+-----+------+
|number|thing|letter|
+------+-----+------+
| 8| bat| h|
| 64|mouse| t|
| -27|horse| x|
+------+-----+------+
和地图
:
val lookup = Map(
"number" -> "id",
"thing" -> "animal"
)
我想选择并重命名列,使number变成id,thing变成animal等等
重命名包含在另一个堆栈溢出问题中:,我确信有一种简单的方法可以在我没有看到的同时进行选择
我原以为这样做可以奏效,但尽管输入是一个字符串,并且它与Seq
而不是map一起工作,但还是会出现很多类型不匹配:
val renamed_selected = someDF.select(
lookup.map(m => col(m._1).as(m._2))
):_*
因此,期望的输出是:
+------+------+
|id |animal|
+------+------+
| 8| bat |
| 64|mouse |
| -27|horse |
+------+------+
谢谢这里有一个方法;使用模式匹配检查
查找中是否存在该名称,如果该列未使用原始名称,则为其指定别名:
val cols = someDF.columns.map(name => lookup.get(name) match {
case Some(newname) => col(name).as(newname)
case None => col(name)
})
someDF.select(cols: _*).show
+---+------+------+
| id|animal|letter|
+---+------+------+
| 8| bat| h|
| 64| mouse| t|
|-27| horse| x|
+---+------+------+
如果在查找中只需要列:
val cols = someDF.columns.collect(name => lookup.get(name) match {
case Some(newname) => col(name).as(newname)
})
someDF.select(cols: _*).show
+---+------+
| id|animal|
+---+------+
| 8| bat|
| 64| mouse|
|-27| horse|
+---+------+
感谢@Psidom-意识到我的问题不是100%清楚。我还想删除地图中没有的列。case None=>None
会涵盖这一点吗?如果您在查找中只需要列,您可以使用collect
,它将删除不匹配的列,而不是map
。查看更新-这是可行的,但我得到了一个类型检查错误-知道如何指定正确的类型吗<代码>类型不匹配,应为:PartialFunction[String,NotInferedB],实际:Nothing=>Column
计算出:`val x:PartialFunction[String,Column]={name:String=>lookup.get(name)match{case Some(newname)=>col name.as(newname):Column}val cols=dataOut.columns.collect{x}`重复问题标志说明:问题不包括如何同时重命名和选择列。