gpt4 book ai didi

scala - 如何将每种类型的列分成两组?

转载 作者:行者123 更新时间:2023-12-01 13:34:45 26 4
gpt4 key购买 nike

我有一个 CSV 输入文件。我们使用以下内容阅读

val rawdata = spark.
read.
format("csv").
option("header", true).
option("inferSchema", true).
load(filename)

这会巧妙地读取数据并构建架构。

下一步是将列拆分为字符串和整数列。怎么办?

如果以下是我的数据集的架构...

scala> rawdata.printSchema
root
|-- ID: integer (nullable = true)
|-- First Name: string (nullable = true)
|-- Last Name: string (nullable = true)
|-- Age: integer (nullable = true)
|-- DailyRate: integer (nullable = true)
|-- Dept: string (nullable = true)
|-- DistanceFromHome: integer (nullable = true)

我想将其分成两个变量(StringCols、IntCols),其中:

  • StringCols 应该有 "First Name","Last Name","Dept"
  • IntCols 应该有 "ID","Age","DailyRate","DistanceFromHome"

这是我试过的:

val names = rawdata.schema.fieldNames
val types = rawdata.schema.fields.map(r => r.dataType)

现在在 types 中,我想循环查找所有 StringType 并在名称中查找列名,对于 IntegerType 也是如此.

最佳答案

在这里,您可以使用底层 schemadataType

按类型过滤列
import org.apache.spark.sql.types.{IntegerType, StringType}

val stringCols = df.schema.filter(c => c.dataType == StringType).map(_.name)
val intCols = df.schema.filter(c => c.dataType == IntegerType).map(_.name)

val dfOfString = df.select(stringCols.head, stringCols.tail : _*)
val dfOfInt = df.select(intCols.head, intCols.tail : _*)

关于scala - 如何将每种类型的列分成两组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44368278/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com