簡體   English   中英

Scala Spark - 如何迭代Dataframe中的字段

[英]Scala Spark - how to iterate fields in a Dataframe

我的Dataframe有幾個不同類型的列(字符串,雙精度,地圖,數組等)。

我需要在某些列類型中執行某些操作,我正在尋找一種很好的方法來識別字段類型,然后執行適當的操作

types: String|Double|Map<String,Int>|...

|---------------------------------------------------------------
|myString1 |myDouble1|     myMap1                   | ...otherTypes                          
|---------------------------------------------------------------
|"string_1"|  123.0  |{"str1Map":1,"str2":2, "str31inmap": 31} |...
|"string_2"|  456.0  |{"str2Map":2,"str22":2, "str32inmap": 32}|...
|"string_3"|  789.0  |{"str3Map":3,"str23":2, "str33inmap": 33}|...
|---------------------------------------------------------------

迭代數據框字段並打印: df.schema.fields.foreach { println }

輸出:

StructField(myString1,StringType,true)
StructField(myDouble1,DoubleType,false)
StructField(myMap1,MapType(StringType,IntType,false),true)
...
StructField(myStringList,ArrayType(StringType,true),true)

所以,我的想法是遍歷字段,如果是我需要執行操作的類型之一(例如在Map類型上),那么我知道字段名稱/列和要采取的操作。

 df.schema.fields.foreach { f =>
     val fName = ?get the name
     val fType = ?get the Type
     print("Name{} Type:{}".format(fName , fType))

      // case type is Map do action X
      // case type is Stringdo action Y
      // ...

    }

這種方法是否有意義檢測我的數據幀上的字段類型,然后根據其類型在df字段上執行不同的操作? 如何讓它工作?

請注意,scala中的打印格式需要%s,在python中你可以使用{}

這應該工作:

 df.dtypes.foreach {  f =>
      val fName = f._1
      val fType = f._2
      if (fType  == "StringType") { println(s"STRING_TYPE") }
      if (fType  == "MapType") { println(s"MAP_TYPE") }
      //else {println("....")}
      println("Name %s Type:%s - all:%s".format(fName , fType, f))

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM