【问题标题】:Access names within pyspark columnspyspark 列中的访问名称
【发布时间】:2021-11-05 00:54:28
【问题描述】:

我需要一些帮助才能访问列中的名称。例如,我有以下架构:

root
 |-- id_1: string (nullable = true)
 |-- array_1: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- id_2: string (nullable = true)
 |    |    |-- post: struct (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]'>

而且没有名字。有什么方法可以访问数组中的名称?结构也会出现同样的问题。这将帮助我循环/使功能更容易。如果可以避免各种模块,那将是有益的。

谢谢

【问题讨论】:

    标签: scala dataframe apache-spark apache-spark-sql rdd


    【解决方案1】:

    您可以使用数据框的架构来查看列名。使用 StructType 和 StructField api。在示例 scala-spark 代码中(根据您的需要优化此代码):

    import org.apache.spark.sql.types._
    
    case class A(a: Int, b: String)
    val df = Seq(("a", Array(A(1, "asd"))), ("b", Array(A(2, "dsa")))).toDF("str_col", "arr_col")
    
    println(df.schema)
    > res19: org.apache.spark.sql.types.StructType = StructType(StructField(str_col,StringType,true), StructField(arr_col,ArrayType(StructType(StructField(a,IntegerType,false), StructField(b,StringType,true)),true),true))
    
    val fields = df.schema.fields
    
    println(fields(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))
    .....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-17
      • 1970-01-01
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多