繁体   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