【问题标题】:Scala Spark - how to iterate fields in a DataframeScala Spark - 如何迭代数据框中的字段
【发布时间】:2017-03-17 09:45:25
【问题描述】:

我的数据框有几个不同类型的列(字符串、双精度、映射、数组等)。

我需要在某些列类型中执行一些操作,我正在寻找一种识别字段类型的好方法,然后执行正确的操作

类型: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 字段执行不同的操作? 如何让它工作?

【问题讨论】:

  • 我认为你需要dtype方法在这里你可以做的是df.dtype.foreach{ pairData => val fName = pairData._1 val fType = pairData._2 //Your code here }
  • 这样,val fNamefType 为空 :/
  • 不可能你做错了什么def dtypes: Array[(String, String)] = schema.fields.map { field => (field.name, field.dataType.toString) }你正在做的方式是更好的方式

标签: scala apache-spark dataframe


【解决方案1】:

注意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))

    }

【讨论】:

  • 这就是我在评论中所说的:CopyPaste
  • 如何获取字段 f 的值?
猜你喜欢
  • 2021-11-25
  • 2017-08-05
  • 1970-01-01
  • 2020-06-03
  • 1970-01-01
  • 2016-05-22
  • 1970-01-01
  • 2018-08-21
  • 2021-07-01
相关资源
最近更新 更多