scala - 如何在 Spark 中取消透视数据框?
问题描述
我有一个具有以下架构的数据框:
subjectID, feature001, feature002, feature003, ..., feature299
假设我的数据框如下所示:
123,0.23,0.54,0.35,...,0.26
234,0.17,0.49,0.47,...,0.69
现在,我想要的是:
subjectID, featureID, featureValue
上面的数据框看起来像:
123,001,0.23
123,002,0.54
123,003,0.35
......
123,299,0.26
234,001,0.17
234,002,0.49
234,003,0.47
......
234,299,0.69
如果我只有几列,我知道如何实现它:
newDF = df.select($"subjectID", expr("stack(3, 'feature001', 001, 'feature002', 002, 'feature003', 003) as (featureID, featureValue)"))
但是,我正在寻找一种处理 300 列的方法。
解决方案
您可以使用列构建一个数组,struct
然后使用explode
将它们转换为行:
import org.apache.spark.sql.functions.{explode, struct, lit, array, col}
// build an array of struct expressions from the feature columns
val columnExprs = df.columns
.filter(_.startsWith("feature"))
.map(name => struct(lit(name.replace("feature","")) as "id", col(name) as "value"))
// unpivot the DataFrame
val newDF = df.select($"subjectID", explode(array(columnExprs:_*)) as "feature")
.select($"subjectID",
$"feature.id" as "featureID",
$"feature.value" as "featureValue")
推荐阅读
- javascript - 转义 javascript 帮助程序的不兼容编码问题
- nats.io - 是否有 NATS Web UI 工具来监控消息?
- python - 具有紧密轴和匹配纵横比的散景图像图
- azure - Azure 开发人员用户同意应用访问公司数据
- javascript - JS 数组排序。如何从数组中删除匹配值
- batch-file - 我不能在 Windows 10 的启动文件夹中删除文件吗
- java - 如何使用插件编译带有 JVM 参数的 Maven JAR 文件?
- python - Left Join 使用 3 个不同的表 - django
- php - 单击 Href 时制作文件
- python - 用另一个列表提供的数据填充多维列表(Python3)