如何从现有Dataframe创建Dataframe并将特定字段设置为Struct类型?

问题描述 投票:2回答:1

我需要从现有的DataFrame创建一个DataFrame,我需要在其中更改模式。

我有一个像DataFrame:

+-----------+----------+-------------+
|Id         |Position   |playerName  |
+-----------+-----------+------------+
|10125      |Forward    |Messi       |
|10126      |Forward    |Ronaldo     |
|10127      |Midfield   |Xavi        |
|10128      |Midfield   |Neymar      |

我使用下面给出的案例类创建了这个:

case class caseClass (
                       Id: Int = "",
                       Position : String = "" ,
                       playerName : String = "" 
                     )

现在我需要在Struct类型下同时制作Playername和position。

我需要用schema创建另一个DataFrame,

| - Id:int(nullable = true)

| - playerDetails:struct(nullable = true)

| | --playername:string(nullable = true)

| | --Position:string(nullable = true)

我通过引用链接https://medium.com/@mrpowers/adding-structtype-columns-to-spark-dataframes-b44125409803执行以下代码来创建新的数据帧

myschema是

  List(
    StructField("Id", IntegerType, true),
    StructField("Position",StringType, true),
    StructField("playerName", StringType,true)
)

我尝试了以下代码

  spark.sparkContext.parallelize(data),
  myschema
)

但我无法实现。

我看到类似的问题Change schema of existing dataframe但我无法理解解决方案。

是否有任何解决方案直接在case类中实现StructType?所以我认为我不需要为创建结构类型值创建自己的模式。

java scala apache-spark dataframe dataset
1个回答
1
投票

可以使用函数“struct”:

// data
val playersDF = Seq(
  (10125, "Forward", "Messi"),
  (10126, "Forward", "Ronaldo"),
  (10127, "Midfield", "Xavi"),
  (10128, "Midfield", "Neymar")
).toDF("Id", "Position", "playerName")

// action
val playersStructuredDF = playersDF.select($"Id", struct("playerName", "Position").as("playerDetails"))
// display
playersStructuredDF.printSchema()
playersStructuredDF.show(false)

输出:

root
 |-- Id: integer (nullable = false)
 |-- playerDetails: struct (nullable = false)
 |    |-- playerName: string (nullable = true)
 |    |-- Position: string (nullable = true)

+-----+------------------+
|Id   |playerDetails     |
+-----+------------------+
|10125|[Messi, Forward]  |
|10126|[Ronaldo, Forward]|
|10127|[Xavi, Midfield]  |
|10128|[Neymar, Midfield]|
+-----+------------------+
© www.soinside.com 2019 - 2024. All rights reserved.