我需要一些幫助來訪問列內的名稱。例如,我有如下模式:
root
|-- id_1: string (nullable = true)
|-- array_1: 陣列 (nullable = true)
|-- element: struct (containsNull = true)
|-- id_2: string (nullable = true)
| |-- post: 結構 (nullable = true)
| |-- value: double (nullable = true)
通過使用
cols = df.columns
我將得到一個根級別的所有名字的串列,
我將得到一個根級別的所有名字的串列。
cols = [id_1, array_1,...] 。
但是,我想訪問例如 "array_1 "中的名字。使用
df.id_1.columns
簡單地回傳
。Column<b'array_1[columns] '>
而且沒有名字。有什么方法可以在陣列中訪問名字嗎?同樣的問題出現在結構上。這將幫助我更容易地回圈/制作函式。如果有可能避免各種模塊,這將是有益的。
謝謝
uj5u.com熱心網友回復:
你可以使用資料框架的模式來尋找列名。使用StructType和StructField apis。在scala-spark代碼的例子中(根據你的需要優化這段代碼):
import org.apache.spark.sql.types._
case class A(a。Int, b: String)
val df = Seq(("a"/span>, Array(A(1, "asd")),("b"。Array(A(2, "dsa")))). toDF("str_col"/span>, "arr_col"/span>)
println(df.schema)
> res19: org.apache.spark.sql.types。 StructType = StructType(StructField(str_col,StringType, true), StructField(arr_col,ArrayType(StructType(a, IntegerType,false), StructField(b, StringType,true)),true)
val fields = df.schema.field
println(field(0).name)
> res22: String = str_col
println(fields(1).dataType.asInstanceOf[ArrayType].elementType)
> res23: org.apache.spark.sql.types。 DataType = StructType(StructField(a,IntegerType, false), StructField(b,StringType,true)
.....
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/309120.html
標籤:
上一篇:<p>在一個典型的Scala上界實體中</p> <preclass="lang-scalas-code-block"><codeclass
